简体   繁体   中英

Can somebody explain this weird loop for me?

I'm newer to c++ and today I looked at a game engine main render loop which looked like this:

for (register unsigned long long i = 0xaull; engine_tick(); kRuntimeStatistics::INSTANCE.FramesSinceStart++, ++ i); 

Why did it have any body and when it is exiting? I thought for loops are for numbers only? And what does 0xaull mean behind the long i?

General case

No the for loop is for any kind of iterative processing. Not only for numbers.

The statement

for (a;b;c) 
   d; 

is (almost) the same as

{
    a;
    while (b) {
        d; 
        c; 
    }
}

The empty body means that the main benefit is already in the a,b and c.

Application to your statement

So for your statement:

for (register unsigned long long i = 0xaull; engine_tick(); kRuntimeStatistics::INSTANCE.FramesSinceStart++, ++ i); 

it's the same as

{
    register unsigned long long i = 0xaull;
    while (engine_tick()) {
        kRuntimeStatistics::INSTANCE.FramesSinceStart++; 
        ++ i;  
    }
}

Several remarks:

  • the empty for body, with semicolon at the end of the line is extremely error prone (I spent a whole night debugging some code once, just to figure out that I didn't see the semicolumn, so that I was mislead by the indentation). I'd therefore recommend to put the semicolumn on the next line with proper indentation, just to draw attention on the potential trap.
  • the register has no longer added value, since the compiler's optimizer do much better job than the manual selection of register variables. It is even deprecated now.
  • the comma operator allows to combine two expression in one. I've translated this in a semi-column for the sake of clarity. Note that the ++i could have been moved to the for body in the original code for the same reason.
  • 0xaull means that it is an hexadecimal literal ( 0x ) of value a (A in hexadecimal is 10) of type unsigned long long .

It will exit when engine_tick() returns false. A while statement doesn't need a body. The ull on the end of 0xa just specifies that its an unsigned long long, while the 0x specifies that its in hex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM