volatile keyword (C)

First head it when doing the SE350 Labs and Emre mentioned how we want to declare variables volatile (I don’t remember why, will have to look into it).gap-in-knowledge

The volatile keyword in C tells the compiler that a variable’s value may change unexpectedly, typically due to external factors.

volatile int c = 3;

Prevents Optimization: It prevents the compiler from optimizing out what it may see as unnecessary reads or writes to the variable.

Tip

The use of volatile in C++ is a way to ensure that variables are accessed directly from memory each time they are referenced in the code, which is critical in ensuring data consistency in multi-threaded applications or in interfacing with hardware where the state can change independently of the program flow.

Common Uses: Used in embedded systems, for hardware access, and in multithreading environments. (Concurrency!)

A Hint to the Compiler, Not the Hardware

The volatile keyword is a directive to the compiler, not to the underlying hardware. It does not affect how the hardware interacts with memory; rather, it affects how the compiler generates code around accesses to the volatile variable.