Volatile Keyword in C
Level 5242 keystrokes
Declares two volatile globals, increments counter five times in a function and then sets flag. It prints Counter: 5, Flag: 1 and the address of counter, which differs from run to run.
C code
// volatile: every access must really read or write memory, the compiler may not cache it// Meant for hardware registers or signal handlers; it does not make code thread-safe1volatile int counter = 0;// A volatile flag that another part of a program could check2volatile int flag = 0;3 // Updates both volatile variables4void increment() { // Repeats 5 times5 for (int i = 0; i < 5; i++) { // Each increment reads and writes memory; the loop cannot be folded into counter = 56 counter++;7 } // Sets the flag once the work is done8 flag = 1;9}10 // Runs the function11increment();// Prints Counter: 512printf("Counter: %d\n", counter);// Prints Flag: 113printf("Flag: %d\n", flag);// Prints the address of counter; it differs from run to run14printf("Address: %p\n", (void *)&counter);Output
Counter: 5 Flag: 1 Address: 0x7fff5fbff8ac
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C code and how often they appear.
;× 10(× 7)× 7"× 6+× 4=× 4,× 3:× 3\× 3%× 3