Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i know if the compiler will optimize a variable?

I am new to Microcontrollers. I have read a lot of Articles and documentations about volatile variables in c. What i understood, is that while using volatile we are telling the compiler not to cache either to optimize the variable. However i still didnt get when this should really be used.
For example let's say i have a simple counter and for loop like this.

for(int i=0; i < blabla.length; i++) {
    //code here
}

or maybe when i write a simple piece of code like this

int i=1; 
int j=1;
printf("the sum is: %d\n" i+j);

I have never cared about compiler optimization for such examples. But in many scopes if the variable is not declared as volatile the ouptut wont be as expected. How would i know that i have to care about compiler optimization in other examples?

like image 886
unkown53 Avatar asked Jul 26 '26 22:07

unkown53


1 Answers

Simple example:

int flag = 1;

while (flag)
{
   do something that doesn't involve flag
}

This can be optimized to:

while (true)
{
   do something
}

because the compiler knows that flag never changes.

with this code:

volatile int flag = 1;

while (flag)
{
   do something that doesn't involve flag
}

nothing will be optimized, because now the compiler knows: "although the program doesn't change flag inside the while loop, it might changed anyway".

like image 159
Jabberwocky Avatar answered Jul 28 '26 11:07

Jabberwocky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!