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

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”.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top