Variables and Constants in C programming
This article will let you know about Variables and Constants in the C programming language.
Variables
A Variable usually stores a data type value in a program such as int, char; etc. The term variable refers to those that can change or vary over time. Basically, a variable is a storage place that allocates some memory to store some form of data.
Note: Variables are written in letters or symbols and represents unknown values. Variables should not be any reserved keywords.
Syntax
type variable_name;
Example
int a = 10;
Here the value of a that is 10 can be changed at any time. Hence it a variable declaration.
#include <stdio.h>
int main () {
/* variable definition */
int x, y;
int z;
float a;
/* initialization */
x = 7;
y = 4;
z = x + y;
printf("value of z : %d \n", z);
a = 8.2/2;
printf("value of a : %a \n", a);
return 0;
}
Output
value of c : 11
value of f : 4.1
Constants
Constants are fixed values which cannot be modified once the values are defined. Constants may be integer constants, floating constants, character constants, string constants, etc.
Constants can be defined in two methods, either by #define or by const keyword. Constants are written in numbers and they represent known values like values in an expression or equation.
Syntax
const type name;
Example
const Pi = 3.141;
Here the value of Pi is 3.141 cannot be changed and it stays constant.
Sample program using define method
#include<stdio.h>
#define PI 3.14
int main()
{
printf("The value of PI is: %f",PI);
return 0;
}
Output
The value of PI is: 3.14
Sample program using keyword method
#include<stdio.h>
int main(){
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;
}
Output
The value of PI is: 3.14