I have a code snippet as given below
static unsigned int ticks; void IRQ_SomeTimer(void) { ticks ++; } int main() { int sav_ticks; sav_ticks = ticks; while (sav_ticks + TIME_TO_WAIT > *(volatile unsigned int *)&ticks); /* Do somethine here */ return 0; }
This compiles and runs on ARM-Mx targets up to optimization level O2, at optimization level O3 the code generated for
while (sav_ticks + TIME_TO_WAIT > *(volatile unsigned int *)&ticks);
is the same as the code generated for
while (sav_ticks + TIME_TO_WAIT > ticks);
Hence the code generated by O3 never comes out of the while loop!! Is this a BUG in Keil armcc(?) I am using Keil U-Vision (MDK ARM 4.73).
By cast I could selectively make the identifier to behave as volatile
... and by doing so, you're lying to your tools. Let there be no doubt about one thing: that variable is volatile, period. So you're putting each and every piece of your code that you made believe otherwise at a considerable risk of breaking, for no good reason at all. Pardon the French, but that's just utterly foolish.
and hence obtaining more optimized code than the one where it is just declared volatile
Looks like you need to hear the applicable words of wisdom, loud and clear:
Premature optimization is the root of all evil. (Donald E. Knuth)