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.
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.
> 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 E2http://en.cppreference.com/w/cpp/language/eval_order
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.
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.