Typo with “cout < myint”. Why does it work?

自闭症网瘾萝莉.ら 提交于 2019-11-29 00:39:54

问题


I have this code and I searched for hours why it fails to print my income

int const income = 0;
std::cout << "I'm sorry, your income is: " < income;

Until I found I missed to write << but wrote <. Why doesn't the compiler detect this and error out? I'm not sure why comparing cout makes sense?


回答1:


integral constant 0 is also a null pointer constant - it can be compared to the result of ostream's operator void *. Note that it'll fail if the constant has any value but 0.




回答2:


The prototypes of the < operator are like :

    ​bool T::operator <(const T& b) const;

So I guess the compiler transtype the argument as the type of this instance. Did you enabled all the warnings like -Wall




回答3:


It does compile with g++ 4.4.3

#include  <iostream>

int main (void)
{
   int const income = 0;
   std::cout << "I'm sorry, your income is: " < income;
}

However, when running it with -Wall (good practice!), I got a funny message:

:~/stack$ g++ test.cpp -o temp
:~/stack$ g++ -Wall test.cpp -o temp
test.cpp: In function 'int main()':
test.cpp:5: warning: right-hand operand of comma has no effect

No clue what it actually does (or tries to do)...




回答4:


When I compile this code using GCC 4.3.4, I see a warning:

prog.cpp: In function ‘int main()’:
prog.cpp:6: warning: right-hand operand of comma has no effect

...though why it's a warning rather than an error, I don't know.

EDIT: In fact, I don't know which comma it's referring to either, because this code:

int const income = 0;
std::cout << "I'm sorry your income is: " < income;

...generates the same warning (see here).



来源:https://stackoverflow.com/questions/5665221/typo-with-cout-myint-why-does-it-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!