Best post to understand Constant in C

Constant in C programming

Constant… as the name suggest that the value of variable will be remain constant throughout the program. When we declare any variable using const keyword then the variable becomes immutable which means we can’t change the value of that variable.

To declare variable as a constant we have to add const keyword before datatype during the initialization.

Syntax and Example

    Syntax:

    const data_type variable = value;

    Example:

    const int var1 = 8;

We have to set the value of constant variable during initialization because if we didn’t do it and if we declare the variable with const keyword, then variable will have garbage value through the program because it is not possible to initialize value to that variable.

Example

    const int var1;  // This will initialized garbage value to variable var1

    var1 = 8;            // This will generate an error because variable has been initialized with garbage value

Following are the types by which we can create constant variable

We can create constant variables with following keywords.

  1. With help of #define preprocessor directive
  2. With help of const keyword.

With help of #define preprocessor directive

We can set an alternate name for variable using #define.

We can also use it to create constant variable.

#define is written in Global Declarations/Definition Section part.

Syntax

    #define identifier_name value

Example

    #include<stdio.h>

    #define var1 8

    void main()

    {

         printf(“Value of var1 is = %d”,var1);

    }

Output :

    Value of var1 is = 8

With the help of const ​keyword

We can create constant variable using const keyword.

We have to add const keyword before datatype during initialization.

Syntax

    const data_type variable = value;

Example

    const int var1 = 8;

Leave a Comment