I found this block of code here :
void work(int n) {
volatile int i=0;
while(i++ < n);
}
void easy() { work(1000); }
void hard() { work(1000*1000*1000); }
int main() { easy(); hard(); }
... but I don't understand why he needs to use the volatile keyword for an integer i. (This is a complete program.) I get that volatile ensures that the value is iread from the main memory, but in this case, since the value is iupdated by the program itself, why does the compiler think it would be nice to do differently (and optimize the while loop)?
source
share