Consider the following embedded C code snippet where a variable is updated inside an Interrupt Service Routine (ISR). What will be the output printed by the main function?
#include <stdio.h> #include <stdbool.h> volatile int flag = 0; void ISR() { flag = 1; } int main() { while (!flag) { // waiting for ISR to set flag } printf("Flag is set to %d\n", flag); return 0; }
Think about how volatile tells the compiler about variable changes outside normal flow.
The volatile keyword tells the compiler that flag can change at any time, such as inside an ISR. Without volatile, the compiler might optimize the loop and never see the change. Here, the loop waits until flag becomes 1, which happens in the ISR, so the program prints "Flag is set to 1".
Why is it important to declare variables shared between main code and an ISR as volatile in embedded C?
Think about what happens if the compiler assumes the variable never changes unexpectedly.
volatile tells the compiler that the variable can change at any time, such as inside an ISR. Without it, the compiler might optimize by caching the variable in a register and never see updates made by the ISR, causing incorrect behavior.
Examine the code below. The variable count is incremented in the ISR and read in main. The program sometimes hangs in the loop. What is the bug?
#include <stdio.h> int count = 0; void ISR() { count++; } int main() { while (count == 0) { // wait for ISR to increment count } printf("Count is %d\n", count); return 0; }
Think about compiler optimizations and how the main loop sees the variable.
Without volatile, the compiler may optimize the loop by caching count in a register, never noticing changes made by the ISR. Declaring count as volatile ensures the main loop reads the updated value.
Which of the following declarations correctly declares a variable status shared between main code and an ISR to ensure proper behavior?
Consider C syntax rules for volatile and static keywords.
All options are valid. volatile can appear before or after int. Adding static limits the variable's scope to the file, which is often good practice in embedded code. So all declarations are correct.
Given the code below, what is the most likely behavior when the flag variable is not declared volatile?
#include <stdio.h>
int flag = 0;
void ISR() {
flag = 1;
}
int main() {
while (!flag) {
// wait for ISR
}
printf("Flag set\n");
return 0;
}Think about compiler optimizations and how they affect variables changed outside normal flow.
Without volatile, the compiler may optimize the loop by reading flag once and caching it, never detecting changes made by the ISR. This causes the loop to hang indefinitely.