简体   繁体   中英

Is this reverse loop is correct in C?

Sometimes in javascript you can see reverse loop like this one:

for ( let i =10; i--;) { ... } 

where i get values from 9 to zero inside the loop.
the boolean evaluation of i-- is true when i > 0,
then the value of (i-1) go inside the loop,
the third argument stay empty as the decrementation of i is allready done before.

in C this should be: (?)

for (int i =10; i--;) { ... }

I'm just wondering if this could be accepted (and working) in C language?

I just want to know if it can be done or not and give an identical result to this for loop:

for (int i =9; i>=0 ;i--) { ... }

Yes, your hypothetical code is valid C and will work as intended. However, beware of the slight variant

for (unsigned int i = 10; i >= 0; i--) { ... }

This is an infinite loop, because an unsigned int cannot be less than zero. JavaScript does not have unsigned types so this can't happen there.

Why would anyone ever write that? Well, suppose you need to crunch a string backwards for some reason, you might naturally write

for (size_t i = strlen(s); i >= 0; i--) { ... use s[i] ... }

but, whoops, size_t is unsigned.

for (int i =9; i>=0 ;i--) 
{ ... }

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