Using the Keyword volatile in C

Consider the following code fragments:

volatile unsigned int done;

main()
{

	done = FALSE;

    while (!done) ;
}

@interrupt void tic2_isr(void)
{
    second = TC2;
    TFLG1 = 0x04;
    done = TRUE;
}

An optimizing compiler knows that done will not change in the main() function. It may decide that, since done is FALSE in the main() function, and nothing in the main() function changes the value of done, then done will always be FALSE, so there is no need to check if it will ever become TRUE. An optimizing comiler might change the line

    while (!done) ;

to

    while (TRUE) ;

and the program will never get beyond that line.

By declaring done to be volatile, you tell the compiler that the value of done might change somewhere else other than in the main() function (such as in an interrupt service routine), and the compiler should not optimize on the done variable.



Bill Rison
2001-02-28