Declare variable as constant in C

CProgrammingServer Side Programming

Variables can be declared as constant using the const keyword or the #define preprocessor directive. Details about these are given as follows.

The const keyword

Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.

A program that demonstrates the declaration of constant variables in C using const keyword is given as follows.

Example

 Live Demo

#include <stdio.h>
int main() {
   const int a;
   const int b = 12;
   printf("The default value of variable a : %d", a);
   printf("\nThe value of variable b : %d", b);
   return 0;
}

The output of the above program is as follows.

The default value of variable a : 0
The value of variable b : 12

The #define preprocessor directive

Variables can be declared as constants by using the #define preprocessor directive as it declares an alias for any value.

A program that demonstrates the declaration of constant variables in C using #define preprocessor directive is given as follows.

Example

 Live Demo

#include <stdio.h>
#define num 25
int main() {
   printf("The value of num is: %d", num);
   return 0;
}

Output

The output of the above program is as follows.

The value of num is: 25
raja
Published on 21-Nov-2018 12:38:03
Advertisements