Reputation: 470
Probably like many, I typed this typo
int a = 0;
cout << a < " "; //note the '<'
However, the MSVC++ compiler threw just a warning
warning C4552: '<' : operator has no effect; expected operator with side-effect
though I expected a compilation error. Is it indeed standard complaint code? Does any implicit type conversion or overloading happen which make the code valid? I am also confused whether <
operator is comparing the string " "
with an integer a
or with the result of cout << a
A related SO post is here.
Upvotes: 4
Views: 216
Reputation:
The <<
operator has a higher precedence than <
, so this is parsed as
(cout << a) < " ";
You are not really comparing a string with an integer. Instead, you are comparing the return value of ostream::operator<<
, which is std::cout
itself, to the string literal. This isn't legal (in the sense that is has an unspecified result, and it is not meaningful) either, clang
warns:
warning: result of comparison against a string literal is unspecified
The reason why it compiles is that up until C++11, std::ostream
can be implicitly converted to void *
. Also, the string literal of type const char[2]
decays into a pointer of type const char *
. So, the <
operator now takes two pointers, which is permitted, although its result is not specified, because the two pointers don't point to the same object.
Upvotes: 7
Reputation: 129454
Actually, since it is (cout << a) < " "
, we're comparing an ostream
with " "
. The ostream
class has an operator to convert it to void *
. You can compare a void *
with a const char *
without cast, so the compiler is happily doing that, then realizing that you are not using the result of the comparison, and issues the warning.
One of those quirky things in C++.
Upvotes: 3
Reputation: 60017
It is down to operator precedence
i.e.
The line equates to (cout << a) < " ";
- Hence the <" "
does nothing!
EDIT
This bit returns an object (cout << a)
returns an object of type ostream
where it does not have an overloaded operator <
, so either the compiler gives up (C++11) or scratches its head amd has a bash at the integer operator (i.e. pointers etc).
Upvotes: 1