×

Const vs Volatile in C

Introduction

Qualifiers are nothing but keywords which are used to modify the properties of a variable. Const and Volatile keywords are qualifiers in C. The Const qualifier is applied to the variable declaration to specify the fact that the value of the variable will not be changed. On the other hand, the volatile qualifier is applied to declaration of any variable to specify that its value can face changes, i.e., it is modifiable.

The differences between the two qualifiers are as follows:

1) Const

The const type qualifier declares an object/variable to be nonmodifiable. But Optimization can be done on it.

2) Volatile

Volatile is a qualifier and a variable should be declared volatile whenever its value could change unexpectedly and no optimization is done on it.

The concept of volatile is somehow not understood well by many programmers and the main reason behind this could be the lack of real-world use of this keyword in typical C programs.

The programs in C are obviously high level, but the point to consider here is that volatile plays a key role in Embedded C Coding which is simply an extension of C language used for development of microcontroller-based applications.

Const in C

The const type qualifier declares an object/variable to be nonmodifiable. But, Optimization can be done on it.

The Objects declared with const-qualified types may be placed in read-only memory by the compiler, and if the address of a const object is never taken in a program, it may not be stored at all. For example,

 

 

Example

#include<stdio.h>
int main()
 {
   const int x = 10; // use of const qualifier
   x = 12;
   return 0;
}

Definition and declaration of Const

TypeDeclarationpointer value change (  *ptr = 100 )pointing value change (  ptr  = &a)
1) Pointer to Variableint * ptr     yes   yes
2) Pointer to Constantconst int * ptrint const * ptr  no   yes
3) Constant Pointer to Variableint * const ptr yes no
4) Constant Pointer to Constantconst int * const ptrno no

Definition of volatile

A volatile is a qualifier in C which basically prevents the compiler from performing any kind of optimization on the targeted object that can change in ways that the compiler cannot determine.

In simple terms, a variable declared as volatile is a volatile variable

  • That can change unexpectedly
  • No assumption regarding its value can be made by the compiler

Declaration of volatile

Syntax : volatile data_type variable name;  OR

                volatile data_type *variable_name;

Eg:

                volatile int p;

                volatile  int *p;

Let’s understand this keyword with the help of a program.

Program 1:  C program without the use of volatile qualifier

#define MEMORY_ADDRESS 0x1000U


int main(void)
{
int val = 0;  // declaration of local variables
int *v = (int *) MEMORY_ADDRESS;


while(1)
{
val = *v;
if (val) 
break;


}
return 0;
}

Code Explanation:

The above code works fine and will give the desired results if there are no optimizations performed by the compiler.

The piece of code will always go and read the value(val) stored at the address pointed by the pointer ‘v’.

But what happens if the compiler optimization occurs here?

If the compiler optimization occurs here and the value is updated by DMA or interrupt which is not under the scope of the compiler, then the compiler optimizes it by keeping a copy of the first read value. The value is kept here in order to avoid multiple memory read operations which are basically time consuming.

What is to understand here is that, in case the value at this address changes then it will never be updated here.

How to avoid this?

In order to avoid this, we need to explicitly inform the compiler that the pointer ‘v’ is volatile and hence the compiler must not optimize it or perform optimization on that pointer.

Program 2:  C program with the use of volatile qualifier

#define MEMORY_ADDRESS 0x1000U


int main(void)
{
int val = 0;    // declaration of local variables
volatile int *v = (int *) MEMORY_ADDRESS; //declaring the variable as volatile


while(1)
{
val = *v;
if (val) 
break;


}
return 0;
}

Code Explanation:

In the above code, we introduce the volatile keyword before declaring the pointer ‘v’. By doing this, we are explicitly telling the compiler that the pointer ‘v’ is volatile and hence the compiler must not optimize it.

Consequences of frequent use of volatile

Volatile qualifier may solve the problem of unwanted optimization done by the compiler but we must keep in mind the consequences it brings with frequent usage.

The volatile variable basically forces the compiler to not keep a copy of read values and fetch a fresh value from memory every time which takes more clock cycles, i.e., more time complexity.

Hence, it is always recommended that a variable should be declared volatile when the value of that variable could change unexpectedly.

Program 3:  C program with the use of Const qualifier

#include <stdio.h>


int main(void)
{
int x = 5;   // declaration of local variables
int y = 15;


int *const ptr = &x;  // use of const qualifier


printf("ptr: %d\n", *ptr);


*ptr = 100;  // valid statement
printf("ptr: %d\n", *ptr);


ptr = &y;	 /* error: assignment of read-only variable ‘ptr’ */
return 0;
}

The Difference between the two qualifiers can be summarized as follows:

3) Const

The const type qualifier declares an object/variable to be nonmodifiable. But Optimization can be done on it.

4) Volatile

Volatile is a qualifier and a variable should be declared volatile whenever its value could change unexpectedly and no optimization is done on it.


Related Topics

How to convert a string to hexadecimal in C

Converting a character array or any string to its respective hexadecimal form is simple. The only thing we have to do is to follow the below steps. Take each character from...

3 minutes read.

Sum of N numbers in C using For loop

Before we move on the program of sum of N numbers, first we have to know about the For Loop statement. The syntax of ‘for’ loop in C programming language is...

3 minutes read.

Break, continue and goto statement in C

Break statement Break statement is used to break the process of a loop (while, do while and for) and switch case. Syntax: break; Example 1 while(test Expression) { // codes if(condition for break){ break; } // codes } Example 2 For(int it, condition,...

1 minute read.

Exponential() in C

Introduction: In C language, there are available many types of functions. The exponential() function is one of them. It is a mathematical function. This article describes using the pow() property to...

3 minutes read.

gets() function in C

gets() is a pre-define or built-in function present in the stdio.h header file. stdio stands for standard input and output. gets() function is used to read a stream and store...

4 minutes read.

C Data type

Data Types in C with Examples Data types are used to define the type of data that a variable can store to perform a specific operation.ANSI C provides three types of...

2 minutes read.

getc() function in C

Getc is one of the file handling technique in C. The Getc() is a C library function gets the next character or new characters  from the specific stream and supports...

4 minutes read.

Ceil and Floor in C

In arithmetic, a rational number is a number that can be expressed as the quotient p/q of two integers. Where q is zero. The set of rational numbers includes all...

6 minutes read.

Volatile in C

Introduction A volatile keyword is a qualifier in C. Qualifiers are nothing but keywords which are used to modify the properties of a variable. Qualifiers are of two types: 1) Const The const type...

3 minutes read.

Why does sizeof(x++) not Increment x in C

Sizeof() is a much-involved operator in C or C++. It is an incorporated time unary administrator which can be utilized to figure the size of its operand. The consequence of...

5 minutes read.

Binomial Coefficient Program in C

What is Binomial coefficient? In the given set of n possibilities, the binomial coefficient(n,k) indicates the order of choosing 'K' results from those possibilities. Binomial coeeficient of posistive n and k...

3 minutes read.

Pointer arithmetic in C

In the C programming language, a pointer is an address which stores a numeric value. Hence, a developer can perform several arithmetic operations on the same just as one does...

4 minutes read.

Dos.h Header File in C Language

Dos.h is a header file in C. Interrupt handling, sound generation, date and time functions, and other tasks can be performed using the functions in this library. This is exclusive to...

4 minutes read.

Find Day from Day in C Without using function

Introduction: In the given article, I find daily in C without using functions. It takes 365 days for the earth to revolve around the sun. It will be close to...

3 minutes read.

How to Merge Array in C?

Introduction Merging arrays is a common task for many developers but might be difficult for beginners of C programming. Fortunately, our guide will show you how to quickly merge arrays in...

6 minutes read.

Call by Value and Call by Reference in C

Call by reference and call by value are two different ways of passing arguments to a function in C programming language. Call by reference means that the called function is...

4 minutes read.

Variable Declaration in C

What is a Variable? A Variable is nothing more than a name for a memory place where data/information can be stored. Any alphabet (from a to z or A to Z), the...

4 minutes read.

If Statement in C

Decision Control Statements We frequently desire one set of instructions to be carried out in one circumstance while another set of instructions to be carried out in a completely different circumstance....

3 minutes read.

Scope of variables in C

Introduction The scope of variables in C can be defined as the scope of reach of a variable, the term scope is used to determine the visible range of an object....

4 minutes read.

Bank management system in C

This is a mini project that is constructed completely using the C language. The bank management system is a beginner friendly project. To construct this user only needs to know...

12 minutes read.