0

The following code :

#include <iostream>
using namespace std;
int test()
{
    cout<<"question \n";
    return 0;
}
int main(){
    cout<<test;
}

Output: question 1

The following code gives 1 everytime I run but I am expecting the output to be 0.

Whereas when I replace the test by test() then I get the expected output. Not sure why is this happening. Please suggest and comment if any rule behind it.

  • 1
    http://stackoverflow.com/questions/17073066/g-calling-function-without-parenthesis-not-f-but-f-why-always-return – JGroven Mar 01 '17 at 05:46
  • Why would lead you to expect `0` in the first case? Certainly not because the function's code finishes with `return 0;`. That would imply you believe the function is executing, which it isn't per your own report of the output simply being `1`, without the word `question` in the output stream before that. – WhozCraig Mar 01 '17 at 05:56
  • Possible duplicate of [g++ "Calling" function without parenthesis ( not f() but f; ). Why always returns 1?](http://stackoverflow.com/questions/17073066/g-calling-function-without-parenthesis-not-f-but-f-why-always-return) – n4m31ess_c0d3r Mar 01 '17 at 06:42

2 Answers2

2

C++ always requires you to use parentheses to call functions. If you omit them, it thinks you want to know the address of the function instead of calling it. The address is then considered to be a (truthy) boolean and gets output as 1. This warning (from gcc -Wall) explains it well:

x.cpp: In function ‘int main()’:
x.cpp:9:11: warning: the address of ‘int test()’ will always evaluate as ‘true’ [-Waddress]
     cout<<test;
           ^
0
std::cout << test;

Outputs 1 because test is a function pointer, it will be converted to bool with std::cout.

MSD
  • 1,409
  • 12
  • 25