Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this compile? cout<"Yes";

Tags:

c++

gcc

#include<iostream>
using namespace std;
int main(){
     cout<"Yes"; 
}

it compiles, but when it runs, it does nothing. this is a compilation error elsewhere. compiler is gcc 4.9.2

compared with

 #include<iostream>
    using namespace std;
    int main(){
         cout<<"Yes"; 
    }

it has a missing '<' but it still compiles.

I expected it to be a compilation error, as with variables, like this:

> 6 6   C:\Users\Denny\Desktop\Codes\compileerror.cpp   [Error] no match for
> 'operator<' (operand types are 'std::ostream {aka
> std::basic_ostream<char>}' and 'int')

this happens with the code below as well.

   #include<iostream>
    using namespace std;
    int main(){
         cin>"Yes"; 
    }

edit: The same thing happens for

#include<iostream>
int main(){
    
    std::cout<"Yes";
}

plus, I enabled compiler warnings and there are none.

like image 380
Miao Wang Avatar asked Nov 03 '21 10:11

Miao Wang


Video Answer


2 Answers

Default C++ standard in GCC<6.1 (which includes your 4.9.2) is gnu++98, while for GCC≥6.1 it's gnu++14 (as documented e.g. here). Thus the latter compiler won't accept this code by default, due to explicit operator bool() being present in the iostreams since C++11 instead of operator void*() in C++98 (see e.g. cppreference).

You could have been warned if you had turned on the warnings:

$ g++-4.8 test.cpp -o test -Wall
test.cpp: In function ‘int main()’:
test.cpp:5:15: warning: value computed is not used [-Wunused-value]
     std::cout < "Yes";
               ^

where test.cpp contains example code:

#include <iostream>

int main()
{
    std::cout < "Yes";
}
like image 59
Ruslan Avatar answered Oct 20 '22 16:10

Ruslan


Prior to C++11, the way that if (std::cin >> var) was supported was the stream objects having an implicit conversion to void *.

So std::cout<"Yes" is evaluated as calling the built in bool operator<(void*, const void*), after applying the conversions std::basic_ios -> void * and const char[4] -> const char* -> const void*.

Since C++11, there is now a rule that an explicit conversion to bool can be used in if, while etc. With that, the operator void* was changed to be explicit operator bool, and overload resolution correctly finds no match for std::cout<"Yes"

like image 37
Caleth Avatar answered Oct 20 '22 18:10

Caleth