Toni
Toni

Reputation: 141

Why does this code need the volatile keyword?

I found this block of code here:

void work(int n) {
  volatile int i=0; //don't optimize away
  while(i++ < n);
}
void easy() { work(1000); }
void hard() { work(1000*1000*1000); }
int main() { easy(); hard(); }

...but I don't understand why it needs to use the volatile keyword for the integer i. (This is the entirety of the program.) I get that volatile enforces that the value of i is to be read from main memory, but in this case, since the value of i is getting updated by the program itself, why would the compiler think it was OK to do otherwise (and optimize away the while loop)?

Upvotes: 5

Views: 102

Answers (1)

user149341
user149341

Reputation:

Because, without the volatile keyword, the compiler is free to observe that the loop does nothing and optimize it away to nothing. The value of i is lost after work() exits, so there is no observable effect of running the loop. (And even if work() were to expose that value, e.g. by returning i, the compiler could still potentially optimize the loop to a single assignment along the lines of i = n.)

With the volatile keyword in place, the compiler is required to retain all accesses to i, so the loop cannot be optimized away.

Upvotes: 10

Related Questions