Volatile Storage class in C

Storage class Volatile in C

The volatile storage class in C is used to specify that a variable’s value can be changed by external factors such as hardware devices or other parts of the operating system. This tells the compiler to avoid certain optimization techniques that might be applied to non-volatile variables, because the value of a volatile variable could change at any time.
Volatile Storage class in C

Volatile Storage class in C

Here is an example of how you can use the volatile storage class:

volatile int flag;

This declares a variable flag of type int that is marked as volatile.

The volatile storage class is often used in situations where a variable is accessed by multiple threads of execution or is being modified by hardware devices. In these cases, the compiler cannot assume that the value of the variable will remain constant and must generate code to re-read the value from memory each time it is accessed.

Volatile Storage Class

It’s important to note that the volatile storage class does not provide any synchronization or mutual exclusion between threads. It simply tells the compiler to generate code that avoids certain optimization techniques. If you need to synchronize access to a shared resource, you will need to use other synchronization mechanisms such as mutexes or semaphores.

#include <stdio.h>// C header file for standard input and output
int m = 0; // initilaizing and declaring the integer a to value 0.
main () // main class
if (m == 0) // This condition will be true
printf (" m = 0 \n ");
else // Else part will be optimized
printf (" m ! = 0 \n ");
return 0; // returning value


m = 0

In this example, the flag variable is marked as volatile to indicate that its value can be modified by external factors. The program enters an infinite loop that only exits when the value of flag becomes non-zero.

This might be useful in a situation where the value of flag is being modified by another thread or by a hardware device. For example, the value of flag might be set to 1 by an interrupt handler when a specific hardware event occurs.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription