The Wayback Machine - https://web.archive.org/web/20240921012609/https://www.geeksforgeeks.org/understanding-volatile-qualifier-in-c/
Open In App

Understanding “volatile” qualifier in C | Set 2 (Examples)

Last Updated : 24 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
 

The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. 

Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time. The system always reads the current value of a volatile object from the memory location rather than keeping its value in a temporary register at the point it is requested, even if a previous instruction asked for the value from the same object. So the simple question is, how can the value of a variable change in such a way that the compiler cannot predict? Consider the following cases for an answer to this question: 

1) Global variables modified by an interrupt service routine outside the scope: For example, a global variable can represent a data port (usually a global pointer, referred to as memory mapped IO) which will be updated dynamically. The code reading the data port must be declared as volatile in order to fetch the latest data available at the port. Failing to declare the variable as volatile will result in the compiler optimizing the code in such a way that it will read the port only once and keep using the same value in a temporary register to speed up the program (speed optimization). In general, an ISR is used to update these data ports when there is an interrupt due to the availability of new data. 


2) Global variables within a multi-threaded application: There are multiple ways for threads’ communication, viz., message passing, shared memory, mail boxes, etc. A global variable is weak form of shared memory. When two threads are sharing information via global variables, those variables need to be qualified with volatile. Since threads run asynchronously, any update of global variables due to one thread should be fetched freshly by the other consumer thread. The compiler can read the global variables and place them in temporary variables of the current thread context. To nullify the effect of compiler optimizations, such global variables need to be qualified as volatile.

If we do not use volatile qualifier, the following problems may arise: 
1) Code may not work as expected when optimization is turned on. 
2) Code may not work as expected when interrupts are enabled and used.

Let us see an example to understand how compilers interpret volatile keyword. Consider the below code. We are changing the value of a const object using a pointer and we are compiling code without optimization option. Hence the compiler won’t do any optimization and will change the value of the const object.

C
/* Compile code without optimization option */
#include <stdio.h>
int main(void)
{
    const int local = 10;
    int *ptr = (int*) &local;

    printf("Initial value of local : %d \n", local);

    *ptr = 100;

    printf("Modified value of local: %d \n", local);

    return 0;
}

When we compile code with “–save-temps” option of gcc, it generates 3 output files:
1) preprocessed code (having .i extension) 
2) assembly code (having .s extension) and 
3) object code (having .o extension). 

We compiled code without optimization, that’s why the size of assembly code will be larger (which is highlighted in red below).

Output: 

  [narendra@ubuntu]$ gcc volatile.c -o volatile –save-temps
[narendra@ubuntu]$ ./volatile
Initial value of local : 10
Modified value of local: 100
[narendra@ubuntu]$ ls -l volatile.s
-rw-r–r– 1 narendra narendra 731 2016-11-19 16:19 volatile.s
[narendra@ubuntu]$

Let us compile the same code with optimization option (i.e. -O option). In the below code, “local” is declared as const (and non-volatile). The GCC compiler does optimization and ignores the instructions which try to change the value of the const object. Hence the value of the const object remains same. 

C
/* Compile code with optimization option */
#include <stdio.h>

int main(void)
{
    const int local = 10;
    int *ptr = (int*) &local;

    printf("Initial value of local : %d \n", local);

    *ptr = 100;

    printf("Modified value of local: %d \n", local);

    return 0;
}

For the above code, the compiler does optimization, that’s why the size of assembly code will reduce.

Output: 

  [narendra@ubuntu]$ gcc -O3 volatile.c -o volatile –save-temps
[narendra@ubuntu]$ ./volatile
Initial value of local : 10
Modified value of local: 10
[narendra@ubuntu]$ ls -l volatile.s
-rw-r–r– 1 narendra narendra 626 2016-11-19 16:21 volatile.s

Let us declare the const object as volatile and compile code with optimization option. Although we compile code with optimization option, the value of the const object will change because the variable is declared as volatile which means, don’t do any optimization. 

C
/* Compile code with optimization option */
#include <stdio.h>

int main(void)
{
    const volatile int local = 10;
    int *ptr = (int*) &local;

    printf("Initial value of local : %d \n", local);

    *ptr = 100;

    printf("Modified value of local: %d \n", local);

    return 0;
}

Output: 

  [narendra@ubuntu]$ gcc -O3 volatile.c -o volatile –save-temp
[narendra@ubuntu]$ ./volatile
Initial value of local : 10
Modified value of local: 100
[narendra@ubuntu]$ ls -l volatile.s
-rw-r–r– 1 narendra narendra 711 2016-11-19 16:22 volatile.s
[narendra@ubuntu]$

The above example may not be a good practical example, but the purpose was to explain how compilers interpret volatile keyword. As a practical example, think of the touch sensor on mobile phones. The driver abstracting the touch sensor will read the location of touch and send it to higher level applications. The driver itself should not modify (const-ness) the read location, and make sure it reads the touch input every time fresh (volatile-ness). Such driver must read the touch sensor input in const volatile manner.

Note: The above codes are compiler specific and may not work on all compilers. The purpose of the examples is to make readers understand the concept.

Related Article : 
Understanding “volatile” qualifier in C | Set 1 (Introduction)
Refer to the following links for more details on volatile keyword: 
Volatile: A programmer’s best friend 
This article is compiled by “Narendra Kangralkar“ and reviewed by GeeksforGeeks team.
 



Previous Article
Next Article

Similar Reads

Understanding "volatile" qualifier in C | Set 1 (Introduction)
In spite of tons of literature on C language, "volatile" keyword is somehow not understood well (even by experienced C programmers). We think that the main reason for this is due to not having real-world use-case of a 'volatile' variable in typical C programs that are written in high level language. Basically, unless you're doing some low level har
5 min read
How does Volatile qualifier of C works in Computing System
Prerequisite: Computing systems, Processing unit Processing Unit:Processing units also have some small memory called registers.The interface between the processor (processing unit) and memory should work on the same speed for better performance of the system.Memory: In memory, there are two types, SRAM and DRAM. SRAM is costly but fast and DRAM is
3 min read
Const Qualifier in C
The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed (which depends upon where const variables are stored, we may change the value of the const variable by using a pointer). The result is implementation-defined if an attempt is made to change a const. Using the const qualifier in C is a
7 min read
Understanding nullptr in C++
Consider the following C++ program that shows problem with NULL (need of nullptr) [GFGTABS] CPP // C++ program to demonstrate problem with NULL #include &lt;bits/stdc++.h&gt; using namespace std; // function with integer argument void fun(int N) { cout &lt;&lt; &quot;fun(int)&quot;; return;} // Overloaded function with char pointer argument void fu
3 min read
Understanding constexpr Specifier in C++
constexpr is a feature added in C++ 11. The main idea is a performance improvement of programs by doing computations at compile time rather than run time. Note that once a program is compiled and finalized by the developer, it is run multiple times by users. The idea is to spend time in compilation and save time at run time (similar to template met
5 min read
Understanding "register" keyword in C
Registers are faster than memory to access, so the variables which are most frequently used in a C program can be put in registers using the register keyword. The keyword register hints to the compiler that a given variable can be put in a register. It's the compiler's choice to put it in a register or not. Generally, compilers themselves do optimi
3 min read
Count number of unique Triangles using STL | Set 1 (Using set)
We are given n triangles along with length of their three sides as a,b,c. Now we need to count number of unique triangles out of these n given triangles. Two triangles are different from one another if they have at least one of the sides different.Example: Input: arr[] = {{1, 2, 2}, {4, 5, 6}, {4, 5, 6} Output: 2 Input: arr[] = {{4, 5, 6}, {6, 5, 4
3 min read
Logical Not ! operator in C with Examples
! is a type of Logical Operator and is read as "NOT" or "Logical NOT". This operator is used to perform "logical NOT" operation, i.e. the function similar to Inverter gate in digital electronics. Syntax: !Condition // returns true if the conditions is false // else returns false Below is an example to demonstrate ! operator: Example: // C program t
1 min read
iswprint() in C/C++ with Examples
The iswprint() is a built-in function in C/C++ which checks if the given wide character can be printed or not. It is defined within the cwctype header file of C++. By default, the following characters are printable: Digits (0 to 9)Uppercase letters (A to Z)Lowercase letters (a to z)Punctuation characters (!"#$%&amp;'()*+, -./:;?@[\]^_`{|}~)Space Sy
2 min read
iswgraph() in C/C++ with Examples
The iswgraph() is a built-in function in C/C++ which checks if the given wide character has a graphical representation or not. It is defined within the cwctype header file of C++. By default, the following characters are graphic: Digits (0 to 9)Uppercase letters (A to Z)Lowercase letters (a to z)Punctuation characters (!"#$%&amp;'()*+, -./:;?@[\]^_
2 min read
btowc() function in C/C++ with Examples
The btowc() is a built-in function in C/C++ which converts a character to its wide character equivalent. It is defined within the cwchar header file of C++. Syntax: wint_t btowc( int ch ); Parameter:The function accepts a single mandatory parameter ch which specifies the single byte character to convert to it's wide character. Return Value: The fun
2 min read
mbrtoc16() in C/C++ with Examples
The mbrtoc16() is a built-in function in C/C++ which converts a narrow multibyte character to a 16 bit character representation. It is defined within the uchar.h header file of C++. Syntax: ssize_t mbrtoc16( char16_t* pc16, const char* s, size_t n, mbstate_t* ps); Parameters: The function accepts four mandatory parameter which are described below:
3 min read
mbrtoc32() in C/C++ with Examples
The mbrtoc32() is a built-in function in C/C++ which converts a narrow multibyte character to a 32 bit character representation. It is defined within the uchar.h header file of C++. Syntax: size_t mbrtoc32( char32_t* pc32, const char* s, size_t n, mbstate_t* ps); Parameters: The function accepts four mandatory parameter which are described below: s
3 min read
wmemset() in C/C++ with Examples
The wmemset() function is a builtin function in C/C++ which copies a single wide character for a specified number of time to a wide character array. It is defined within the cwchar header file in C++. Syntax: wmemset(des, ch, count) Parameters: The function accepts three parameters which are described below. des: It specifies to the wide character
2 min read
wcsspn() function in C/C++ with Examples
The wcsspn() is a built-in function in C/C++ which returns the length of maximum initial segment of the wide string that consists of characters present in another wide string. It is defined within the cwchar header file of C++. Syntax: wcsspn(des, src) Parameters:The function accepts two mandatory parameters as described below. des: specifies to a
2 min read
cauchy_distribution a() in C++ with Examples
The cauchy_distribution::a() function is an inbuilt function in C++ STL which is used to returns the distribution parameter associated with Cauchy distribution. The class cauchy_distribution is present in header file random. Before going to the syntax of the function, brief introduction to Cauchy Distribution. Cauchy Distribution A random variable
2 min read
getdate() and setdate() function in C with Examples
setdate() Method: getdate() function is defined in dos.h header file. This function fills the date structure *dt with the system's current date. Syntax struct date dt; getdate(&amp;dt); Parameter: This function accepts a single parameter dt which is the object of structure date. Return Value: This method does not return anything. It just gets the s
2 min read
asctime() and asctime_s() functions in C with Examples
asctime() function The asctime() function returns the pointer to the string that contains the information stored in the structure of the struct tm type. This function is used to return the local time defined by the system in string format. This function is defined in &lt;time.h&gt; header file. Syntaxchar *asctime(const struct tm* tm_ptr);Parameter
3 min read
ctype.h(&lt;cctype&gt;) library in C/C++ with Examples
As string.h header file contains inbuilt functions to handle Strings in C/C++, the ctype.h/&lt;cctype&gt; contains inbuilt functions to handle characters in C/C++ respectively. Characters are of two types: Printable Characters: The characters that are displayed on the terminal. Control Characters: The characters that are initiated to perform a spec
5 min read
C fopen() function with Examples
The fopen() method in C is a library function that is used to open a file to perform various operations which include reading, writing, etc. along with various modes. If the file exists then the fopen() function opens the particular file else a new file is created. SyntaxThe syntax of C fopen() is: FILE *fopen(const char *file_name, const char *mod
4 min read
&lt;cfloat&gt; float.h in C/C++ with Examples
This header file consists of platform-dependent and implementation specific floating point values. A floating point has four parts. Sign Its value can be either negative or non-negative. Base It is also known as radix of exponent representation which represents different numbers with single number i.e. 2 for binary, 10 for decimal, 16 for hexadecim
4 min read
Internal static variable vs. External static variable with Examples in C
The static variable may be internal or external depending on the place of declaration. Both kinds of static variables are stored in initialized data segments. Internal Static Variables Internal Static variables are defined as those having static variables which are declared inside a function and extend up to the end of the particular function. Synt
2 min read
Implicit Type Conversion in C with Examples
Prerequisite: Data Types, Type Conversion Implicit Type Conversion is also known as 'automatic type conversion'. It is done by the compiler on its own, without any external trigger from the user. It generally takes place when in an expression more than one data type is present. In such condition type conversion (type promotion) takes place to avoid
5 min read
Difference between Argument and Parameter in C/C++ with Examples
Argument An argument is referred to the values that are passed within a function when the function is called. These values are generally the source of the function that require the arguments during the process of execution. These values are assigned to the variables in the definition of the function that is called. The type of the values passed in
4 min read
Nested Loops in C with Examples
A nested loop means a loop statement inside another loop statement. That is why nested loops are also called "loop inside loops". We can define any number of loops inside another loop. 1. Nested for Loop Nested for loop refers to any type of loop that is defined inside a 'for' loop. Below is the equivalent flow diagram for nested 'for' loops: Synta
5 min read
Predefined Macros in C with Examples
According to C89 Standard, C programming language has following predefined macros: __LINE__ Macro: __LINE__ macro contains the current line number of the program in the compilation. It gives the line number where it is called. It is used in generating log statements, error messages, throwing exceptions and debugging codes. Whenever the compiler fin
4 min read
exit(0) vs exit(1) in C/C++ with Examples
exit is a jump statement in C/C++ language which takes an integer (zero or non zero) to represent different exit status. There are two types of exit status in C/C++: Exit Success: Exit Success is indicated by exit(0) statement which means successful termination of the program, i.e. program has been executed without any error or interrupt. #include
2 min read
Jagged Array or Array of Arrays in C with Examples
Prerequisite: Arrays in C Jagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These type of arrays are also known as Jagged arrays. Example: arr[][] = { {0, 1, 2}, {6, 4}, {1, 7, 6, 8, 9}, {5} }; Below are the methods to implement the j
3 min read
fpclassify() method in C/C++ with Examples
The fpclassify() function are defined in header math.h header in C and cmath library in C++. This function is used to get the value of type int that matches one of the classification macro constants (depending on the value of x). Syntax: int fpclassify(int x); int fpclassify(float x); int fpclassify(double x); int fpclassify(long double x); Paramet
2 min read
Long Division Method to find Square root with Examples
Given an integer X which is a perfect square, the task is to find the square root of it by using the long division method. Examples: Input: N = 484 Output: 22 222 = 484 Input: N = 144 Output: 12 122 = 144 Approach: Long division is a very common method to find the square root of a number. The following is the stepwise solution for this method: 1. D
10 min read