开发者

Is the empty statement in programming languages as C, Java, ... no-op in Assembler?

A few days ago I saw that for ( ; ; ) results in an infinite loop. That made me wonder about two things.

  1. Is the empty statement ( ; ) no-op in assembler
  2. Why is it evaluated as "开发者_C百科true" in the for example given above?


Answering from a C perspective here:

No, ; does not translate into a no-op instruction. No-op instructions (such as nop) are explicit assembly level instructions which tend to actually do something (in that they consume time, though not necessarily affect any stored state within the CPU).

The for(;;) snippet is a for loop with defaults for each of the three sections. You can think of the ; in this case as not being an empty statement but a separator for the sections (a).

  • The first section (initialisation) has a default of "do nothing".
  • The second section is a condition under which the loop will continue. Its default is to continue forever.
  • The third section, the steps to take before beginning a subsequent iteration, is also "do nothing".

I have, in the past, been guilty of the heinous crime of using things like:

#define ever ;;
#define forever for (;;)

so that I could write my infinite loops as:

for(ever) { ... }
forever { ... }

I wouldn't do that nowadays of course.


(a) A "true" empty statement along the lines of:

if (condition) {
    a = b;
    ;
}

will also probably not translate to a no-op. More than likely it will not result in any code at all.

Keep in mind this is based on fairly common behaviour. In terms of C, ; can generate any lower level code it wants as long as it doesn't affect the "virtual machine" that is the C environment. It may, for example, increase a hidden line number variable and update coverage statistics if you have profiling enabled.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜