I would like to increment two variables in a for
-loop condition instead of one.
So something like:
for (int i = 0; i != 5; ++i and ++j) do_something(i, j);
What is the syntax for this?
If you want to test both conditions, use the && operator. What is happening in your code is related to how the comma operator , works. Both i < p and j < q are evaluated, but only the result of the 2nd expression j < q is checked by the for loop.
Yes, I can declare multiple variables in a for-loop. And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas. Do not forget to end the complete initialization statement with a semicolon.
In C, I generally use i++ in a for loop, because it feels more natural. It's a natural shortening of i = i + 1 or i += 1 , as far as I'm concerned. If you don't use the value if the expression, both i++ and ++i are otherwise equivalent in C.
For example, incrementing 2 to 10 by the number 2 would be 2, 4, 6, 8, 10. 2. An increment is also a programming operator to increase the value of a numerical value. In Perl, a variable can be incremented by one by adding a ++ at the end of the variable.
A common idiom is to use the comma operator which evaluates both operands, and returns the second operand. Thus:
for(int i = 0; i != 5; ++i,++j) do_something(i,j);
Now having wrote that, a commenter suggested it was actually some special syntactic sugar in the for statement, and not a comma operator at all. I checked that in GCC as follows:
int i=0; int a=5; int x=0; for(i; i<5; x=i++,a++){ printf("i=%d a=%d x=%d\n",i,a,x); }
I was expecting x to pick up the original value of a, so it should have displayed 5,6,7.. for x. What I got was this
i=0 a=5 x=0 i=1 a=6 x=0 i=2 a=7 x=1 i=3 a=8 x=2 i=4 a=9 x=3
However, if I bracketed the expression to force the parser into really seeing a comma operator, I get this
int main(){ int i=0; int a=5; int x=0; for(i=0; i<5; x=(i++,a++)){ printf("i=%d a=%d x=%d\n",i,a,x); } } i=0 a=5 x=0 i=1 a=6 x=5 i=2 a=7 x=6 i=3 a=8 x=7 i=4 a=9 x=8
Initially I thought that this showed it wasn't behaving as a comma operator at all, but as it turns out, this is simply a precedence issue - the comma operator has the lowest possible precedence, so the expression x=i++,a++ is effectively parsed as (x=i++),a++
Thanks for all the comments, it was an interesting learning experience, and I've been using C for many years!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With