Difference Between Constants and Variables in C
The constants and variables in C are both used to store data. So it is essential to know the difference between the variables and constants in C so that we can decide which one to use based on the situation.
In this article, we will discuss the basic difference between a constant and a variable in C language.
Variables in C
A variable in simple terms is a storage place that has some memory allocated to it. It is used to store some form of data and retrieve it when required. Different types of variables require different amounts of memory and have some specific set of operations that can be applied to them.
C Variable Declaration
type variable_name;
type variable1_name, variable2_name, variable3_name;
A variable name can consist of alphabets (both upper and lower case), numbers, and the underscore ‘_’ character. However, the name must not start with a number.
Example of C Variable
C
#include <stdio.h>
int main()
{
char a123 = 'a' ;
float b;
int _c, _d45, e;
printf ( "%c \n" , a123);
return 0;
}
|
Constants in C
The constants are those variables or values in the C which cannot be modified once they are defined in the program.
- They have fixed values till the program’s life.
- We can only assign value to the constant in the declaration.
- There can be any type of constant like integer, float, octal, hexadecimal, character constants, etc.
Example of C Constant
C
#include <stdio.h>
#define val 10
int main()
{
const float floatVal = 5.8;
const char charVal = 'a' ;
printf ( "Integer Constant: %d\n" , val);
printf ( "Floating point Constant: %f\n" , floatVal);
printf ( "Character Constant: %c\n" , charVal);
return 0;
}
|
Output
Integer Constant: 10
Floating point Constant: 5.800000
Character Constant: a
Difference between Constant and Variables
The following table lists the differences between the constant and variables in C:
Constant
|
Variables
|
A constant is a variable or value that cannot be altered once defined. |
A variable is a name associated with some memory location. |
A constant is used to hold the fixed values which we can retrieve later but cannot change. |
A variable is used to hold some value that can be changed according to the requirement. |
The constants are generally stored in the text segment as they are read-only |
The variables are stored inside a data segment, heap, or stack depending on the environment it is declared in. |
We can only assign a value to the constant while defining it. |
We can assign value to the variable anytime. |
A constant can be defined by using #define or const keyword. |
A variable can only be defined using the standard variable definition syntax. |
Example: #define pi 3.14
const int pi = 3.14;
|
Example: int var = 25;
var = 10;
|
Last Updated :
10 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...