Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is my best approach to determining compiler behaviour for empty infinite loops?

Tags:

c++

c++11

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.

like image 530
Lightness Races in Orbit Avatar asked May 15 '15 15:05

Lightness Races in Orbit


1 Answers

How about looking at the assembly language output from your compiler?

g++ -std=c++0x x.cpp -S

outputs:

.L2:
        jmp     .L2

and

clang++-3.5 -S -std=c++11 x.cpp

outputs:

.LBB0_1:                                # =>This Inner Loop Header: Depth=1
        jmp     .LBB0_1
like image 119
G. Allen Morris III Avatar answered Nov 16 '22 12:11

G. Allen Morris III