+ 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?

25th Sep 2019, 7:34 AM
æ±éąšç•™ć
æ±éąšç•™ć - avatar
6 Respostas
+ 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...
25th Sep 2019, 7:41 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 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
25th Sep 2019, 8:24 AM
Brave Tea
Brave Tea - avatar
+ 1
Thx~
25th Sep 2019, 11:00 AM
æ±éąšç•™ć
æ±éąšç•™ć - avatar
0
but i havnt define the variable myClass đŸ€”how can it output 1,where does the value 1 come from?
25th Sep 2019, 7:44 AM
æ±éąšç•™ć
æ±éąšç•™ć - avatar
- 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.
25th Sep 2019, 2:51 PM
Ű§Ù„ŰŻÙ„ŰŽ Ű§Ù„ŰŻÙ„ŰŽ
Ű§Ù„ŰŻÙ„ŰŽ Ű§Ù„ŰŻÙ„ŰŽ - avatar