c++ ostream problem

I wrote these code in VS 2012, and the result puzzles me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main(void)
{
	int n=2;
	std::cout << n << std::endl;           // output:
	std::cout << ++n << std::endl;         // 3
	std::cout << --n << std::endl;         // 2
	                                      
        std::cout << ++n << std::endl << --n;  // 2   2
	std::cout << n++ << std::endl << --n;  // 1   2
	std::cout << n++ << std::endl << --n;  // 1   2
	system("pause");
	return 0;
}


I think the third output should be 3 and 2, but why I got this result? how the vs output the result?

plus, I found somewhere, they say we should prefer use '\n' than std::endl, because std::endl with flush the stram, what does the flush mean? is it bad? and when should we flush the stream? (I think input '\n' is quicker than std::endl)


std::cout << n++ << std::endl << n--;
// I run the code below in Eclipse, is post an waring, says:
operation on 'n' may be undefined [-Wsequence-point]

and VS 2012 doesn't post anything, why?
Last edited on
As gcc (which must be what your Eclipse runs) correctly warned you, the effect of executing any of the statements
1
2
3
std::cout << ++n << std::endl << --n; 
std::cout << n++ << std::endl << --n; 
std::cout << n++ << std::endl << --n;

are undefined.

Anything at all can happen because you're attempting to modify the same scalar variable twice, with no synchronization.

See http://en.cppreference.com/w/cpp/language/eval_order or any other docuemntation on the order of evaluation in C++
Topic archived. No new replies allowed.