0
0
Embedded Cprogramming~5 mins

Volatile variables in ISR context in Embedded C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Volatile variables in ISR context
O(n)
Understanding Time Complexity

When using volatile variables in interrupt service routines (ISRs), it's important to understand how often the code accesses these variables.

We want to see how the number of operations changes as the program runs and interrupts occur.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


volatile int flag = 0;

void ISR() {
    flag = 1;  // Set flag when interrupt occurs
}

int main() {
    while (1) {
        if (flag) {
            flag = 0;  // Clear flag
            // Handle event
        }
    }
}
    

This code sets a volatile flag in an ISR and checks it repeatedly in the main loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The infinite while loop in main repeatedly checks the volatile flag.
  • How many times: The loop runs continuously, checking the flag many times per second.
How Execution Grows With Input

As the program runs longer, the number of flag checks grows proportionally with time.

Input Size (time units)Approx. Operations (flag checks)
1010 checks
100100 checks
10001000 checks

Pattern observation: The number of operations grows linearly with time spent running the loop.

Final Time Complexity

Time Complexity: O(n)

This means the number of operations grows directly with the length of time the program runs.

Common Mistake

[X] Wrong: "The volatile keyword makes the flag check faster or reduces how often it runs."

[OK] Correct: Volatile only tells the compiler not to optimize away the variable; it does not change how often the code runs or how many times the flag is checked.

Interview Connect

Understanding how volatile variables behave in loops and ISRs helps you write reliable embedded code and shows you can reason about how code runs over time.

Self-Check

"What if we replaced the volatile flag with a non-volatile variable? How would the time complexity and behavior change?"