difference

can anybody tell me what's the difference between these 2 codes?

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main () {
	bool test;
	cout << (1 < 2) ? "true" : "false" << endl;
	cin.get();
	return 0;
}


result an error:

...my documents\visual studio 2008\projects\test\test\test.cpp(6) : error C2563: mismatch in formal parameter list
...my documents\visual studio 2008\projects\test\test\test.cpp(6) : error C2568: '<<' : unable to resolve function overload


1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main () {
	bool test;
	cout << ((1 < 2) ? "true" : "false") << endl;
	cin.get();
	return 0;
}


result:

true



can anybody explain what's goin' on when the brackets is not been used?
Operator precedence rules dictate how to parse an expression. The operator :? (level 15 on cppreference) has lower precedence than the operator << (level 7 on cppreference)

so

cout << (1 < 2) ? "true" : "false" << endl;

is parsed as

( cout << (1 < 2) ) ? "true" : ("false" << endl) ;

The compiler then fails to compile the subexpression "false" << endl because there is no operator<< that takes an array of 6 char on the left and some function compatible with endl on the right.

http://en.cppreference.com/w/cpp/language/operator_precedence
thanks for your help... :)
Topic archived. No new replies allowed.