Me myself and I
Me myself and I

Reputation: 4070

Why am I always getting output as 1 when printing a function?

I am wondering why I'm always getting output as 1 when I print this function. Here is the code:

#include <iostream>
using namespace std;

int main() {
    int x(int());
    cout << x; // 1
}

It always prints out one. Why? I was expecting it to output 0 as ints are defaulted to 0. So why 1?

Upvotes: 5

Views: 201

Answers (2)

Matteo Italia
Matteo Italia

Reputation: 126867

int x(int());

is a case of "most vexing parse"; you think it's a declaration of an int (int x) initialized to the default value for ints (int()); instead, the compiler interpret it as a declaration of a function returning an int which takes as a parameter a (pointer to) function that takes no parameters and returns an int (you can get hairy declarations explained by this site, or gain some more understanding about C type declarations here).

Then, when you do:

cout << x;

x here decays to function pointer, but there's no overload of operator<< that takes a function pointer; the simplest implicit conversion that gives some valid overload of operator<< is to bool, and, since a function pointer cannot have a 0 (NULL) value, it is evaluated to true, which is printed as 1.

Notice that I'm not entirely sure that such a code should be compiled without errors - you are taking the address of a function that is only declared and not defined; it is true that it cannot be evaluated to anything other than true, but in line of principle you should get a linker error (here masked by the optimizer, that removes any reference to x, since it isn't actually used).


What you actually wanted is:

int x=int();

Upvotes: 6

Mankarse
Mankarse

Reputation: 40633

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

This is a standard conversion sequence consisting of a function-to-pointer conversion followed by a boolean conversion.

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

Upvotes: 2

Related Questions