Compilation error comparing integer with string?

Probably, like many, I typed this typo

int a = 0; cout << a < " "; //note the '<' 

However, the MSVC ++ compiler threw only a warning

warning C4552: '<': operator is not valid; expected operator with side effect

although I was expecting a compilation error. Is this the standard complaint code? Is there any implicit conversion or overloading of types that make the code valid? I am also confused if the operator < compares the string " " with the integer a or with the result cout << a

Related SO mail here .

+4
source share
3 answers

The << operator has higher priority than < , so it is parsed as

 (cout << a) < " "; 

You are not really comparing a string to an integer. Instead, you compare the return value of ostream::operator<< , which is std::cout , to a string literal. This is not legal (in the sense that it has an unspecified result, and it does not make sense), clang warns:

 warning: result of comparison against a string literal is unspecified 

The reason for compiling is that before C ++ 11, std::ostream can be implicitly converted to void * . In addition, a string literal of type const char[2] splits into a pointer of type const char * . Thus, the < operator now accepts two pointers, which is allowed, although its result is not specified, since the two pointers do not point to the same object.

+7
source

Actually, since this is (cout << a) < " " , we are comparing ostream with " " . The ostream class has an operator that converts it to void * . You can compare void * with const char * without actuation, so the compiler gladly does this, and then realizes that you are not using the result of the comparison, and issues a warning.

One of these fancy stuff in C ++.

+3
source

Before the operator precedence

i.e.

The line is (cout << a) < " "; - Therefore, <" " does nothing!

EDIT

This bit returns an object (cout << a) returns an object of type ostream , where it does not have an overloaded operator < , therefore either the compiler refuses (C ++ 11) or smooths its head amd, has bash for an integer operator (i.e. pointers, etc.).

+1
source

Source: https://habr.com/ru/post/1492600/


All Articles