Declare variable as constant in C


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("
The 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

Updated on: 26-Jun-2020

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements