Mister Jojo
Mister Jojo

Reputation: 22320

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--) { ... }

Upvotes: 2

Views: 176

Answers (2)

zwol
zwol

Reputation: 140659

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.

Upvotes: 2

user366312
user366312

Reputation: 16928

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

Upvotes: 1

Related Questions