+ 1
why the output is 1
#include <iostream> #include <string> using namespace std; int myClass() { int x = 5; return x; }; int main() { cout << myClass ; return 0; } //why the output is 1?
6 odpowiedzi
+ 3
It's because you use the myClass function without parentheses. Use myClass() instead. Also it's seems like a bad idea to call a function a class...
+ 1
i believe it is because when you cout << function; (without the () )
you ask if it exists. so the return is 1 because true
not completely certain though
+ 1
Thx~
0
but i havnt define the variable myClass 🤔how can it output 1,where does the value 1 come from?
- 2
name of the function is a pointer and pointer is convertible to bool.
so cout << myClass is checking if(myClass) since myClass has some address it evaluates to true. true is further convertible to integer, hence you are getting 1 as output.
try this
int *ptr = nullptr;
cout << ptr; // output 0, since ptr is nullptr. All non-zero values are true in C/C++ other languages.