HELP PLZ
HELP PLZ

Reputation: 41

left to right evaluation of statements inside of a for loop separated by comma

Are these both codes same? These statements inside of for loop are written in same line separated by comma. Will they be evaluated for left to right?

Also i wanted to ask can i use as many as statements inside of for loop separated by comma. Like for(i=0, j=0, k=0; .......) ?

for(i=0, j= strlen(s)-1; i<j; i++, j--){ 
     c=s[i];
     s[i]=s[j];
     s[j]=c;
}

and

for(i=0, j= strlen(s)-1; i<j; i++, j--)
      c=s[i],s[i]=s[j],s[j]=c;

Upvotes: 3

Views: 134

Answers (2)

ouah
ouah

Reputation: 145899

, operator is evaluated left to right and there is a sequence point between the evaluation of the left and the right operand, so it means both codes are equivalent.

Upvotes: 3

abligh
abligh

Reputation: 25139

The C comma operator evaluates each of the two operands, discarding the result of the first and returning the second. With more than one comma, the operator is left associative so the effect is an evaluation from left to right.

Your second example will thus do the same thing as your first example. However it is poor style because there is no reason to use the comma operator, unlike i=0, j-strlen(s)-1 within the body of the for statement, where a semicolon could not have been used.

Upvotes: 6

Related Questions