Reputation:
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.
Upvotes: 0
Views: 64
Reputation: 1407
std::cout << test;
Outputs 1 because test is a function pointer, it will be converted to bool with std::cout
.
Upvotes: 0
Reputation: 48572
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;
^
Upvotes: 2