What is Constant Qualifier in C?

Constant qualifier is used to declare a variable as contant. If we dont want a variable to change its value then we can use constant qualifier to make that variable to hold a value throughout the program.

Constant changes behavoior of a variable making it not to be modified.

Const qualifier tells the compiler that the value residing in the variable should not be changed.


Syntax of const Qualifier

const data_type variable_name=value;

When to Use const Qualifier

  • If you dont want to change the value of a variable.
  • In case of calling a function by passing pointer as its parameter then const is being used to safeguard the variable. Ex: int function_name( cont int *value );

Constant Qualifier in c Example Program

#include<stdio.h>
int main()
{
 const int num=10;
 printf("\n\n\tNumber=%d\n\n",num);
}

Output

	Number=10
Constant Qualifier in c Example Program

Code explanation:

Include stdio.h header file for outputting the result.
Declare a constant variable with const qualifier and initialize it with a value.
Output the value stored in that variable.


What is Volatile Qualifier in C?

When we declare a variable to be volatile, then it tells the compiler that the variable value can be altered at any moment without any action being taken by the code. Thus compiler treats volatile variables to be special variables and also it cannot assume any value for them.

The value for the volatile variables is taken through memory instead of register. Thus it cannot be optimized. The main usage of volatile variables is during thread communication and in the situation where the value of the variable is updated externally by other entities.


Syntax of Volatile Qualifier

volatile data_type variable_name;

The value of variable temp might get altered through digital thermometer attached to the computer.


Volatile Qualifier in c Example Program

#include<stdio.h>
int main()
{
 volatile int num=10;
 printf("\n\n\tNumber=%d\n\n",num);
}

Output

	Number=10
Volatile Qualifier in c Example Program

Code explanation


People also ask for

Where are constant variables stored in C?

Constant variables are stored in stack section of a c program.

Why is constant qualifier needed in c?

To make a variable whose value should not be changed.

What does volatile do?

Volatile prevents compilers to optimize that variable as variable’s value may change.

When should I use volatile in C?

Variables having volatile qualifier wont be considered for optimization as its value changes that compiler cannot decide what optimizations to perform.