Volatile keyword and why it matters in Embedded C - Time & Space Complexity
When using the volatile keyword, it affects how the program reads and writes variables that can change unexpectedly.
We want to understand how this impacts the number of operations the program performs as input changes.
Analyze the time complexity of the following code snippet.
volatile int flag = 0;
void wait_for_flag() {
while(flag == 0) {
// wait here
}
// flag changed, continue
}
This code waits in a loop until the flag variable changes, which might happen outside this code.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
whileloop repeatedly checks theflagvariable. - How many times: It runs until
flagchanges from 0 to non-zero.
The loop runs as many times as it takes for flag to change. If the change is delayed, the loop runs longer.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks of flag |
| 100 | About 100 checks of flag |
| 1000 | About 1000 checks of flag |
Pattern observation: The number of checks grows directly with how long the program waits for flag to change.
Time Complexity: O(n)
This means the time spent waiting grows linearly with how many times the loop checks the variable before it changes.
[X] Wrong: "The compiler will always check the variable fresh, so volatile is not needed."
[OK] Correct: Without volatile, the compiler might optimize by reading the variable once and reusing it, causing the loop to never see changes made outside.
Understanding how volatile affects loops and variable access shows you know how hardware and compilers interact, a key skill in embedded programming.
"What if we removed the volatile keyword? How would the time complexity and program behavior change?"