Okay, I have a simple problem. I want to print the value of N twice and then increase it (this is just a chunk of a bigger program, ie the one in which it makes sense to do that), however, the output is "1 0".

#include "stdafx.h"
#include <iostream>

using namespace std;

int main() {
	int n = 0;

	cout<<n<<"       "<<n++<<endl;


	int asdf;
	cin>>asdf;

}

Now, if after reading the code the output isn't strange to you then my understanding of C++ is probably very wrong and I'm missing something obvious.
If it is, then someone please explain why it does that, because as far as I know, it should first print the value of N, which is 0, print it again, which is also 0 and then it should increase the value of N.

Yes, I know, I could've just made it look like

cout<<n<<"         "<<n<<endl;
n++;

but I'm wondering why the first way of doing it wont work.


Thanks in advance

EDIT: Oh and sorry if this has been asked already, I just didn't know what to search for when I've encountered the problem

>> Now, if after reading the code the output isn't strange to you then my understanding of C++ is probably very wrong and I'm missing something obvious.

Well, as you've rightly guessed, the output is as expected... :)
You may now be wondering why this happens - well, when you have any sort of cascaded operations, C++ evaluates the statement in the right-to-left direction, and executes it in the left-to-right direction. In other words, evaluation is right associative

If you know about operator overloading, then this is what happens in a cascaded cout statement:

cout << n << n++;

is converted to:

operator<<(operator<<(cout, n), n++);

According to your code, n = 0, so that statement would look like:

operator<<(operator<<(cout, 1), 0);

From this you can probably guess that the the innermost output operations get executed first, moving outwards, i.e left-to-right, or in other words, execution is left-associative.

So, after outputting 1 onto the screen, the statement reduces to:

operator<<(cout, 0);

, which will output 0 onto the screen, which is how you get your output....

See this for more info... (page 441 of that book)

Hope this helps!

Ah I think I understand it now... thanks alot.
Btw. the link doesn't seem to work.

Ah I think I understand it now... thanks alot.
Btw. the link doesn't seem to work.

Glad it helped! :) ... Sorry about the link, here's the page.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.