0

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

2
  • Can you put the arr declaration ? Commented Oct 20, 2015 at 11:44
  • Readability, and therefore maintainability, is an important aspect of programming. Which one would you think was easier to read and understand (and therefore easier to maintain)? Commented Oct 20, 2015 at 11:45

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.