Hi there All, I have a problem which seemed to be defying explanation, but I have come up with a theory. Could I possibly have some feedback on whether the following is likely, plausible, possible, untrue or downright rubbish? If one reads the contents of a CAN or ADC chip register at a particular address, then the label volatile is placed upon that address to prevent the compiler optimising out repeat readings of the address. If one reads the contents of the address into a variable, then the compiler would automatically treat the contents of this variable with similar care. Is it possible that there has been an oversight with statements where the contents of a variable depend on the contents of a volatile by way of an if statement, ie...
normal_var=volatile_var;
normal_var=voltile_var; if (normal_var=0x00) { another_normal_var+=1; }
My question is what will happen to the lines...
i *= 2; write_to_dac(i);
Hi Hans, You suggest that it should be untouched by the optimiser. No. Nobody was suggesting that. In Mike's message is says... You are suggesting that the compiler might optimize it...Well, it's not going to happen because ADC is volatile. ...which I took to mean that Mike was suggesting it would be untouched by the optimiser. You somehow seem to believe that there's no middle ground between constant and volatile... - ordinary variables. I am happy with the fact that variable may, well vary (for want of a better word). I am also happy with the opimiser optimising algorithms where all the numbers start off within the code. I am less happy (in the knowledge sense) or what happens to algorithms which manipulate variables that have been loaded with numbers from external sources such as ADC's and CAN chips. From what I can make out... 1) We assign the volatile qualifier to anything coming from an external source. 2) The compiler will not assume a variable is volatile unless you explicitly define it as such. ...so given this piece of code...
extern int volatile ADC; int i; for (;;) { i = ADC; i *= 2; write_to_dac(i); }
for (;;) { i = ADC; }
for (;;) { i *=2; write_to_DAC(i); }
You've broken your original code into pieces in a way the optimizer is already forbidden to do it, regardless of any usages of the "volatile" keyword. The two parts of the code that really exist are:
i = ADC
i += 2; write_do_DAC(i)
In Mike's message is says... You are suggesting that the compiler might optimize it...Well, it's not going to happen because ADC is volatile. ...which I took to mean that Mike was suggesting it would be untouched by the optimiser. Wrong. Words taken out of context. I still suggest that you come up with a real-world example of C code and possibly undesirable optimizations by the compiler on that code. Then there would be a basis for discussion. If it's not possible to think of such an example, then the problem does not exist. Regards, - mike