increment operator output doubt

I'm new to C++ and have been having little problem with increment operator

1
2
  int b=2;
  cout<<++b<<"\t"<<b++;


Output:
4 2

But,i expect the output to be:
3 3

since, ++b first increments b and then returns it, therefore 3 should be printed. Whereas, b++ first returns b which prints 3 and then increments b, which makes b=4 in memory.

If anyone could explain what is it that i'm missing it'd be of great help.
Last edited on
If this snippet of code came from a resource, take that resource and throw it away, find a better one.

The result of your snippet of code is left undefined by the standard: it's a programming error, so trying to predict the result is an exercise in futility.

What's precisely wrong:
Your assumption is that ++b is evaluated before b++. This assumption is unfounded. Either expression may be evaluated first or even evaluated concurrently with the others, i.e., the evaluations of b++ and ++b may be interleaved. There is no correct answer.
Last edited on
To get the expected output you can move the increments outside of the cout statement.

1
2
3
4
int b=2;
++b;
cout << b << "\t" << b;
++b;

Even if your code had worked I still would have preferred to write it like this because it's easier to read.
Last edited on
> But,i expect the output to be:
> 3 3
>
> since, ++b first increments b and then returns it, therefore 3 should be printed. Whereas, b++ > first returns b which prints 3 and then increments b, which makes b=4 in memory.

You would get that expected behaviour with C++17 (when C++17 compilers become available).
As of now (pre-C++17), it is undefined behaviour.

C++17:
In a shift operator expression E1<<E2 and E1>>E2, every value computation and side-effect of E1 is sequenced before every value computation and side effect of E2 http://en.cppreference.com/w/cpp/language/eval_order


Details: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0145r3.pdf
shanky001it is helpful to consider the "Prcedence of operators" published in Tutorials http://www.cplusplus.com/doc/tutorial/operators/

As it is stated there, the postfix increment is performed left-to-right before the prefix one, which is performed right- to- left. Thus in your example first of all there will be performed output of b. Than will be done b++ (i.e. b=3), than ++b (b=4) and after that the b obtained is directed to output.
Chonard, precedence does not decide the order of evaluation.
so its actually related to compiler, thanks for the reference
@mbozzi
@Peter87
@JLBorges
@Chonard
> so its actually related to compiler,

It is related to the language specification; compilers (are expected to) conform to the specification.
C++17 (currently a Draft International Standard) is a revision of the current specification, and will supersede it.

More information: http://en.cppreference.com/w/cpp/language/eval_order
Topic archived. No new replies allowed.