Are you volatile?

The volatile keyword in C is used to inform the compiler that the value of a variable may change at any time, without any action being taken by the code the compiler finds nearby. This is often necessary in embedded systems where certain memory locations are mapped to device registers or in multi-threaded applications where a variable may be modified by another thread.

When you declare a variable as volatile, the compiler avoids optimizations that are based on the assumption that the value of the variable cannot change unexpectedly. As a result, each time the variable is accessed, the compiler will always fetch its value from the memory location instead of relying on a cached value that might be out-of-date.

Let's consider an example where volatile is useful. Suppose we have a signal handler that changes a flag, and a main loop that waits for this flag to change:

#include <stdio.h>
#include <signal.h>
#include <unistd.h>

volatile sig_atomic_t flag = 0;

void signal_handler(int signum) {
    flag = 1;
}

int main() {
    signal(SIGINT, signal_handler);
    while (!flag) {
        // Main loop does something
    }
    printf("Signal received, flag set to %d\n", flag);
    return 0;
}

In this code, flag is declared with volatile because it is modified by signal_handler, which could be called asynchronously. Without volatile, the compiler might optimize the loop in main in such a way that it never fetches the updated value of flag.

Compiling and Running the Code

To compile and run this C program on a Linux system, you can use gcc from the bash shell. Here's how you might do it:

  1. Write the Code: Save the above code in a file, say volatile_example.c.

  2. Compile the Code: Open a terminal and compile the code using gcc:

     gcc -o volatile_example volatile_example.c
    
  3. Run the Program: Run the compiled program:

     ./volatile_example
    

    Now, if you send a SIGINT signal (typically by pressing Ctrl+C) to the program while it's running, the signal handler will set flag to 1, and the loop in main will exit, printing the message.

0
Subscribe to my newsletter

Read articles from Jyotiprakash Mishra directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jyotiprakash Mishra
Jyotiprakash Mishra

I am Jyotiprakash, a deeply driven computer systems engineer, software developer, teacher, and philosopher. With a decade of professional experience, I have contributed to various cutting-edge software products in network security, mobile apps, and healthcare software at renowned companies like Oracle, Yahoo, and Epic. My academic journey has taken me to prestigious institutions such as the University of Wisconsin-Madison and BITS Pilani in India, where I consistently ranked among the top of my class. At my core, I am a computer enthusiast with a profound interest in understanding the intricacies of computer programming. My skills are not limited to application programming in Java; I have also delved deeply into computer hardware, learning about various architectures, low-level assembly programming, Linux kernel implementation, and writing device drivers. The contributions of Linus Torvalds, Ken Thompson, and Dennis Ritchie—who revolutionized the computer industry—inspire me. I believe that real contributions to computer science are made by mastering all levels of abstraction and understanding systems inside out. In addition to my professional pursuits, I am passionate about teaching and sharing knowledge. I have spent two years as a teaching assistant at UW Madison, where I taught complex concepts in operating systems, computer graphics, and data structures to both graduate and undergraduate students. Currently, I am an assistant professor at KIIT, Bhubaneswar, where I continue to teach computer science to undergraduate and graduate students. I am also working on writing a few free books on systems programming, as I believe in freely sharing knowledge to empower others.