Hello,
I have some doubts about compiler optimizing C code. This is more related to the field of embedded system.
Code:
int a, b;
void experiment() {
a = 8;
b = a * 7;
if(a == 8)
printf("a equals 8!!!");
else
printf("A is NOT 8!!!");
}
In above code, inside the function experiment() value of a is not changing. So extreme optimization will change the code as follows
Code:
int a, b;
void experiment() {
a = 8;
b = a * 7;
printf("a equals 8!!!");
}
So in these cases it is necessary to declare variable a as volatile, since a could be modified by an external even ISR or multi threaded application.
This is clear for me. But what if the code is as follows
Code:
int a, b;
void experiment() {
a = 8;
b = a * 7;
if(a == 8)
printf("a equals 8!!!");
else {
printf("A is NOT 8!!!");
a = 5;
}
}
here a is changed to 5 inside else statement.
Q1. Will this avoid optimization?
Another example of using volatile is in loops.
Code:
void delay() {
int x = 1000;
while(x > 5)
x--
}
I have seen in a tutorial that, if x in not declared volatile, compiler will optimize this.
Why????
Q2. Here value of x is modifying inside while loop. So what's the necessary of volatile here??