CIsForCookies
CIsForCookies

Reputation: 12837

for loop execution within the loop condition, c++

I wanted to fill up an int array with 121 ints, from 0 to 120. What is the difference between:

  1. for(int i = 0; i < 122; arr[i] = i, i++){} and
  2. for(int i = 0; i < 122; i++){arr[i] = i;} ?

I checked it and except warning: iteration 121u invokes undefined behavior, which I think isn't related to my question, the code compiles fine and gets the expected results

EDIT: thanks for all who noticed the readability problem, that's true of course, but I meant to see if there is a different interpretation for these 2 lines, so I checked both of these lines in C to assembly and they look identical

Upvotes: 0

Views: 58

Answers (2)

SingerOfTheFall
SingerOfTheFall

Reputation: 29976

None, the result will be the same. The first construction uses a comma operator; the left side of a comma operator is sequenced before the right side, so arr[i] = i, i++ is well-defined

The second one is easier to read, though, especially if one chooses to omit the {} completely:

for(int i = 0; i < 122; arr[i] = i, i++); //this ; is evil, don't write such code. 

Also, if you want to fill up 120 elements, you should use i < 120.

Upvotes: 1

therainmaker
therainmaker

Reputation: 4343

The end result from both of the lines will be the same. However, the second one is better as the first one sacrifices readability for no gain.

When people read through code, they expect for loops to be in manner you have written in the second line. If I was stepping through code and encountered the first line, I would've stopped for a second to look at why an empty for loop was being run, and then would've realised that you are setting the variable in the for loop itself using the comma operator. Breaks the flow while reading code, and so won't recommend it.

Upvotes: 1

Related Questions