×

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 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.

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; 
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; 
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 that it brings with frequent usage.

The volatile variable forces the compiler to not keep a copy of 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.


Related Topics

Type Conversion in the C

The process of changing one data type to another in the C programming language is known as "type conversion." The type conversion method is only executed on data types that...

4 minutes read.

Format Specifier in C

Format Specifier in C Format specifiers can be described as an operator that is used to print the data referred by any object or variable in combination with the printf ()...

3 minutes read.

Multi-dimensional Arrays in C

Multi-dimensional Arrays in C The C programming allows the concept of multi-dimensional arrays. The data within the multidimensional arrays are stored in the tabular form, that is, in a row significant...

3 minutes read.

FIFO Example in the C Language

FIFO is an acronym that means "First In, First Out." It is a data structure handling method in which the first element is handled first, and the last element is...

3 minutes read.

Pointer to pointer in C

A pointer to another pointer is another type of multiple indirections and a chain of many pointers. Generally, a pointer consists of the address of the variable. Once a pointer to...

4 minutes read.

Flexible Array Members in a Structure in C

There is flexibility to declare array from c99 generation onwards that declaration of the collections can be made possible without even mentioning its dimension, which means that the displays are...

4 minutes read.

Ceil function in C

Introduction In the C Programming Language, the ceil function is a library function which is used to obtain the ceil value, i.e., it returns the smallest integer that is greater than...

4 minutes read.

2f in C language

Float data type in c: Double-precision floating-point numbers with up to 17 significant digits are stored in the FLOAT data type. FLOAT is equivalent to C's double data type and IEEE...

3 minutes read.

Type Casting in C

Type casting is a way to convert a variable from one data type to another data type.Syntax: (type) expression;     Example: #include <stdio.h> int main() { int a,b; float sum; printf("Example of Type Casting\n"); printf("Enter any integer nos:"); scanf("%d",&a,&b); sum=a+b; printf("Sum: %f",sum); return 0; } Output Example...

1 minute read.

For Loop in C Programming Examples

The Syntax of the For Loop for (initialization statement; termination condition; modifying (increment/ decrement) statement) {       /* main body of the For loop */     } In for loop, the initialization command...

6 minutes read.

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.

Multilevel Feedback Queue Scheduling (MLFQ) CPU Scheduling

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

3 minutes read.

File Handling in C

File Handling is used to open, read, write, search and close file.  C files I/O functions handles data on secondary storage device. File handling function: There are varioushandling functions in C. Function Operation fopen() It is...

4 minutes read.

Bit Stuffing Program in C

What is a Bit Stuffing? The process of inserting one or more extra bits (0) into data is known as bit stuffing. To provide signalling information to a recipient, these are...

3 minutes read.

C Program to find the Roots of a Quadratic Equation

What is Quadratic Equation: Equations of degree 2 in polynomial form are called quadratic equations. A, B, and C are the coefficient variables in the equation, which is written as ax2...

3 minutes read.

Kruskal algorithm in C

Given a weighted graph, Kruskal's algorithm generates a spanning tree with the lowest possible weights. Start by creating an edge list for the given graph, including the weights. Sort the...

3 minutes read.

Calendar application in C

Introduction to the calendar application We all are familiar with the calendar. It plays a crucial role in our daily life. We run toward the calendar whenever we want to know...

6 minutes read.

Builtin functions of GCC compiler

Certain built-in functions are present in the GCC compiler. These features are as follows: Function_ built in_popcount (x) The number of 1s in data of the integer type can be counted using...

3 minutes read.

Socket Programming in C

Socket programming is a process that connects the two or more nodes on a networking communication with respective to each other. One of the sockets that determines the socket (I.e.,...

5 minutes read.

C Program Swap Numbers in cyclic order Using Call by Reference

The three integers that the user entered in cyclical sequence are swapped in this tutorial using call by reference. C Program: #include <stdio.h> void cyclic_Swap ( int *X, int *Y, int *Z ); int...

2 minutes read.