What pragma to preclude dropping empty while() loops?

Go To Last Post
5 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Am I correct in assuming that an empty while(condition) loop will *never* be optimized-out (dropped) by the compiler if the condition involves an I/O register?

that is
while(a > b); might be dropped in some optimization modes, but
while(ANYIOREGISTER & SOMEBITMASK); will not, no matter the optimization mode?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The only thing that's special about I/O registers is that they are
volatile, an attribute which prevents most of the analysis which
allows loops to be optimized away. You can achieve the same
effect by declaring your variables volatile.

It's still theoretically possible for a loop based on an I/O register
(volatile variable) test to be optimized away, but it's hard to come up
with an example which isn't rather contrived.

Keep in mind that there's a third possibility -- if the compiler can
determine that a loop is executed some fixed number of times, it can
replace it with that many repetitions of the loop body. I don't know
whether you consider that being "optimized away" or not.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

For delays, it's better to use the functions from . They

are well-timed, and as they are written in inline assembly, the

compiler won't ever touch'em.

Otherwise, the following *ought* to work to, though it's still

potentially subject to loop unrolling:

while (...) asm volatile("nop" ::);

Jörg Wunsch

Please don't send me PMs, use email if you want to approach me personally.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

dl8dtl wrote:
Otherwise, the following *ought* to work to, though it's still

potentially subject to loop unrolling:

while (...) asm volatile("nop" ::);


This is what I do - and it hasn't failed me yet :)

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thanks all.