caneralp 0 Posted December 17, 2014 Share Posted December 17, 2014 Hello, I have a problem with optimization. Can anyone help me? my code is below which is for loop and delaying. volatile unsigned int b; b = 30000; do { b--; }while(b != 0); normally unless I define b as a volatile variable, it doesnt work, Can anyone explain why it doesnt work? Also when I debug step by step, It works. Also without this loop it works but I can not see the changes. Thanks Quote Link to post Share on other sites
enl 227 Posted December 17, 2014 Share Posted December 17, 2014 Without volatile: The compiler recognises that the loop has no net effect and that the end result will be that b==0. Therefore, the loop is replaced with an assignment. With volatile: the compiler presumes that, even if it can't see it, something, somewhere, may be looking at the value of b other than the code in the loop. Therefore, it a.) compiles the code exactly as written, with b.) no optimizations, and c.) not using a register for the variable (it will always be in RAM, with the associated time penalty for access) Fred, spirilis, tripwire and 1 other 4 Quote Link to post Share on other sites
roadrunner84 466 Posted December 18, 2014 Share Posted December 18, 2014 why use delay loops if you can use timers and low power mode to achieve a similar goal? tripwire 1 Quote Link to post Share on other sites
tripwire 139 Posted December 18, 2014 Share Posted December 18, 2014 why use delay loops if you can use timers and low power mode to achieve a similar goal? Also, if you really need a busy wait it's better to use the __delay_cycles() intrinsic function. That way the compiler definitely won't optimise it out and the length of the delay is clearly defined. Quote Link to post Share on other sites
rockets4kids 204 Posted December 18, 2014 Share Posted December 18, 2014 Also, this is not an optimization problem. The optimizer is doing exactly what it is supposed to do here. Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.