An infinite loop with an empty body has undefined behaviour in C++11. I don't know whether it also does in C, so let's say I'm writing embedded firmware in C++11 (I know, unlikely, but bear with me).
If my main
were simply a:
while (true) {}
and the rest of the device's functionality were handled by interrupts, what approaches can I take in order to discover whether my implementation makes this loop safe and meaningful? Remembering that, per the standard, an implementation is free to do whatever it wants in this case, including removing the loop entirely.
Assume it's not clearly stated in the implementation's documentation, as I've never seen that.
Or is this a lost cause, and I should hack a workaround?
volatile unsigned int dummy = 0;
while (true) {
// Make the loop well-defined...
dummy++;
// ...with a trivial operation that'll hardly ever even happen
sleep(42*86400);
}
I recognise that embedded developers historically don't give much thought to this kind of thing, instead assuming a more "down to earth", "common sense" approach from their compiler. But I prefer to code rigourously to standards, to avoid surprises as much as possible.
__asm nop _endasm
will be considered as "side effect" (well, it's out of standard I guess) – Melbavolatile
memory space (like a hardware register) might be a good idea to ensure that the loop body doesn't get optimized away under any circumstances. – Amorosovolatile sig_atomic_t
nor lock-free atomics have an unspecified value inside interrupt handlers, and become undefined if you modify them. – Redstonewhile(true){}
is not UB in C11; its "may be assumed to terminate" clause excludes loops whose controlling expression is a constant expression. – Dysphoriawhile(1);
construct. I've never seen problems with it. – Transnationalhere: goto here;
? – Sharpeyedvolatile int dummy=1; while(dummy);
This question also discuss the topic a bit: stackoverflow.com/questions/4437527 – Transnational