Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...