Why is it when you want to increment by one, it's variable++ but if you want to increment by other value, you have to spell it out fully like variable = variable +2? Why can't I just do a straight variable + 2 in the for loop?
for (int x = 0; x<y; x++)
works fine
for (int x = 0; x<y; x+2)
doesn't work
for (int x = 0; x<y; x = x +2)
works?
gcjr
May 25, 2020, 8:24am
2
for (int x = 0; x<y; x+=2)
You can also use this style
for (int x = 0; x<y; x +=2)
...R
Why can't I just do a straight variable + 2 in the for loop?
The pre and post increment/decrement operators have an implicit reassignment.
'x + y' has no such reassignment.
They are just shorthand notations:
// these lines all increment by one:
i++;
i+=1;
i=i+1;
// these lines increment by two:
i+=2;
i=i+2;
gcjr
May 25, 2020, 10:17am
6
TimMJN:
They are just shorthand notations:
i think it's in C because the DEC processor C was developed on had in/decrement machine instructions.
of course it seems obvious to have such an operation in any language, just as it was to the DEC processor architects