[C++] Quick question about infinite for-loop

9 posts

Flag Post

Ahoy :)
I’m currently attending a C++ programming course, and I stumbled upon a way to make an infinite loop I haven’t seen before:

 
for (;;) 
{
   //infinite loop
}

My question is simple… Why does this work / what is the logic behind it?

 
Flag Post

That would mean pretty much, inititialize nothing, check nothing (missing boolean defaults to true in for loops) and increment nothing.

for(A;B;C) {
    D();
}

// Would be equivalent to:

A;
while(B) {
    D();
    C;
}

// With the only difference that a missing B dafaults to true in a for loop.

E.g.

for(;;) {
    foo();
}

// Is equivalent to:

while(true) {
    foo();
}
 
Flag Post

Or more simply:

Why does it work? Because you have NO EXIT CONDITION.

QED

 
Flag Post

I think he was wondering why the syntax works at all.

 
Flag Post

Someone, thanks.

Draganviper, correct :)

 
Flag Post
Originally posted by draganviper:

I think he was wondering why the syntax works at all.

Because an empty statement is still a valid statement.

It’s called NOOP (NO OPeration)

 
Flag Post
Originally posted by Draco18s:
Originally posted by draganviper:

I think he was wondering why the syntax works at all.

Because an empty statement is still a valid statement.

It’s called NOOP (NO OPeration)

I don’t think an empty for loop would actually use the NOOP statement, it would be pointless. Loop structures are high level structures, on the assembly level it’s just clever goto statements.

 
Flag Post
Originally posted by Drakim:
Originally posted by Draco18s:
Originally posted by draganviper:

I think he was wondering why the syntax works at all.

Because an empty statement is still a valid statement.

It’s called NOOP (NO OPeration)

I don’t think an empty for loop would actually use the NOOP statement, it would be pointless. Loop structures are high level structures, on the assembly level it’s just clever goto statements.

Ahem. for(;;) contains 3 NOOP statements, also known as empty statements (outside of the for() statement, you can use ; on an otherwise empty line as a NOOP).

As a for() statement requires 3 statements to be made, you must pass three NOOP statements, if you wish it to be empty (e.g. infinite loop).

 
Flag Post

I think Drakim was talking about the actual generation of a nop instruction by the compiler (versus simply including no statement). For example, for(;;) in AS3 would generate something like this:

jump L1

L2: 
label         	

L1: 
jump L2

There is no nop instruction in that bytecode. I don’t know if it’s the same in C++ or if it would vary between compilers.