odd issue with increment operator in postfix

I was writing code like this:

ifstream input("data.txt");

char ar1[80], ar2[80];
int n = 0;

while ( !input.eof() )
input >> ar1[n] >> ar2[n++];


(Assume ar1 and ar2 are big enough to hold data from input.)

Obviously, I was expecting ar1[0] to hold the first character of the input, and ar2[0] to hold the second, and so forth. The thing is, the first time through the loop, n seems to be incremented FIRST, even though I put a postfix increment operator.... So! Can anyone explain what is actually going on in this piece of code?

P.S: Btw, how do I put code in a box like some people usually do?




http://www.cplusplus.com/articles/firedraco1/
It's appreciable that you notice we use code tags, as opposed to a lot of people who just act as though they don't exist. (Compliment)
See what happens if you change that n++ to an n+1, and then you increment n afterwards. Does your code work in such a case?
AFAIK, postfix incrementation is the last operation to be performed in all cases. But operator precedence, especially with ++/--, is difficult to speak on. So I can't say for sure.
The thing is, the first time through the loop, n seems to be incremented FIRST, even though I put a postfix increment operator


What's even more strange, is it won't always work that way! It depends on the compiler/situation.

You should refrain from compounding statements like this for this very reason.

So! Can anyone explain what is actually going on in this piece of code?


It has to do with sequence points and other language details I'm fairly fuzzy on. Basically, the compiler is allowed to evaluate expressions in any order between sequence points as long as the operators are evaluated in the right order.

The end of this sequence point is marked with the semicolon.

What's happening is the compiler is evaluating ar2[n++] before it's evaluating ar1[n], which is perfectly legal for it to do because the operators are all still evaluated in the proper order.

Other things you shouldn't do:

1
2
AFunction( a, ++a );  // EDIT: actually this might be okay, but I don't recommend it in any case
b = ++a + a++;


Relevent link: http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.15

P.S: Btw, how do I put code in a box like some people usually do?


Strange how you could figure out bold tag, but not the code tag =P

[code]Your code here[/code]
Last edited on
Topic archived. No new replies allowed.