2

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--) { ... }
E_net4
  • 27,810
  • 13
  • 101
  • 139
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • 2
    `for (int i=10; i--;)` is correct and will do the same as the js version. However, it is better to write the loop in a more readable form: `for (int i=9; i>=0; i--)` – Aziz Jul 02 '20 at 22:42
  • @kaylum I don't have a c compiler at disposal – Mister Jojo Jul 02 '20 at 22:43
  • 2
    You could also use the [`-->` operator](https://stackoverflow.com/questions/1642028/what-is-the-operator-in-c) ;) – chtz Jul 02 '20 at 23:01
  • 1
    Yes, it is correct. it is also the best way to reverse-index an array. (whithout needing the ugly ssize_t) – wildplasser Jul 02 '20 at 23:23

2 Answers2

2

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.

zwol
  • 135,547
  • 38
  • 252
  • 361
  • I thought you were referring to `for (int i =10; i--; )`. That, I do use. Some people have problems with it, but it's a common idiom. Comment deleted. – ikegami Jul 03 '20 at 00:18
1
for (int i =9; i>=0 ;i--) 
{ ... }
user366312
  • 16,949
  • 65
  • 235
  • 452