Why do I always get output as 1 when printing a function?

Hi guys, I'm new to C ++ (and SO) and wondered why I always get output as 1 when I print this function. Ok here is the code:

#include <iostream> using namespace std; int main() { int x(int()); cout << x; // 1 } 

He always prints one. What for? I expected it to output 0 since ints defaults to 0. So why 1?

+4
source share
2 answers
 int x(int()); 

- this is the case of the most unpleasant parsing ; you consider this an int ( int x ) declaration, initialized to the default value for ints ( int() ); instead, the compiler interprets it as an declaration of a function returning an int , which takes as a parameter a function a (pointer), which takes no parameters and returns int (you can get hairy declarations explained by this site or get a better idea of ​​type C declarations here )

Then when you do:

 cout << x; 

x splits into a pointer function here, but there is no operator<< overload that takes a pointer to a function; the simplest implicit conversion that gives some valid operator<< overload is bool , and since the function pointer cannot be 0 ( NULL ), it evaluates to true , which prints as 1.

Please note that I'm not quite sure that such code should be compiled without errors - you take the address of a function that is only declared and not defined; it is true that it cannot be evaluated by anything other than true , but in principle you should get a linker error (here it is masked by an optimizer that removes any link to x , since it is not actually used).


In fact, you wanted:

 int x=int(); 
+2
source

The function is converted to bool and printed as the value of bool . The function is at a non-zero address, so the conversion creates true .

This is a standard conversion sequence consisting of converting a function to a pointer followed by a Boolean conversion.

The sequence is executed because there is no better overloaded operator<< .

+1
source

All Articles