1

While browsing through foreign code I came across this:

      for(i = 0; i < len; i++,j)

Can anybody tell me what the "j" does here? I guess it's something simple, but I don't understand the meaning. "j" is declared as a uint16_t and initialized with 0.

Tom L.
  • 932
  • 2
  • 9
  • 30
  • 4
    It doesn't do anything. Probably it's some left over from a previous version of the code. If you are in charge of the code or can commit changes, remove the `j`. – pmg Apr 22 '14 at 11:25
  • 1
    See here for the *comma operator*: http://stackoverflow.com/questions/1737634/c-comma-operator – alk Apr 22 '14 at 11:27
  • 2
    It's an evidence for a bad code review. – alk Apr 22 '14 at 11:28
  • Thanks, I didn't know this was called the comma operator. @alk, would you want to post this as an answer (even though it's obviously and obvious one ;-) )? – Tom L. Apr 22 '14 at 11:30
  • possible duplicate of [What does the comma operator \`,\` do in C?](http://stackoverflow.com/questions/52550/what-does-the-comma-operator-do-in-c) – alk Apr 22 '14 at 11:33
  • @alk I think I tend to agree, though I am thinking still. OP did not know what happens when we simply put `j;` as a statement or whether it was his ignorance about the comma operator. – bubble Apr 22 '14 at 11:40
  • The canonical description of `for` is `for (init-expression ; condition-expression ; loop-expression)`. Merely stating `j` is not invalid (comma-operator or not), but it is only *evaluated* in the center `condition-expression`. – Jongware Apr 22 '14 at 11:45
  • It was not knowing the comma operator – Tom L. Apr 22 '14 at 11:48

4 Answers4

2

The following code is valid

for(i=0; i<len; i++,j++);

and is equivalent to

for(i=0; i<len; i++,j)
{
j++;
}

which is further equivalent to

//NOTE-there is no j after the i++;

    for(i=0; i<len; i++)
    {
    j++;
    }

So there is no need to write j in your for(statement). The j written in your for(statement), has no function. So it can be omitted without effecting the program.

NOTE- the following code is valid and wont give any error but it is meaningless.

10;
nishantbhardwaj2002
  • 757
  • 2
  • 6
  • 18
1

C allows one to initialize/update multiple variables in a for loop, separated by commas. For example: for(i =0, j=0; i < 4; i++, j++) This statement isn't updating anything, and is useless.

jsoberg
  • 167
  • 12
0

It is redundant, to put it simply.

bubble
  • 3,408
  • 5
  • 29
  • 51
0

This code is valid,It will not give any error.And you can skip j also.There is no use of this.

Umesh
  • 11
  • 3