why it shows me "1"

Sep 19, 2017 at 4:25am
it's always show me "1"....can you help me

1
2
3
4
5
6
7
8
9
10
11
#include<iostream>
using namespace std;
int b();
int main(){
cout<<b;
return 0;
}
int b()
{
cout<<"need to show on consolve";
}
Sep 19, 2017 at 5:04am
Change line 5 to cout << b();
You are not calling the function, doing it your way, but are displaying an non-initialized variable.
Sep 19, 2017 at 6:33am
you are definately right...can you help me one more time ?
Sep 19, 2017 at 6:34am
Actually, what cout << b; does is write out the address of the function b()

Last edited on Sep 19, 2017 at 6:59am
Sep 19, 2017 at 6:38am
i know i'm wrong when i type
cout<<b;
but can you explain why does it show me
1
anytime
Last edited on Sep 19, 2017 at 6:39am
Sep 19, 2017 at 6:51am
Actually, what cout << b; does is write out the address of the function b()
No: the name b is ultimately converted to bool and printed. That is, the overload std::ostream::operator<<(std::ostream&, void*) isn't applicable and
std::ostream::operator<<(std::ostream&, bool) is called instead.

This is because function pointers aren't convertible to void*.

Since the address of a function will never be NULL (i.e., 0), it is treated as true and printed as 1.
Last edited on Sep 19, 2017 at 6:55am
Sep 19, 2017 at 7:07am
it is a little bit higher than i thought....can not get it after all....anyway i appreciate that
Sep 19, 2017 at 12:55pm
phongvants123, I'm not sure what your last post meant, but your b() function is supposed to return an int. Right now you don't have it returning anything.

If you have no use for an int, maybe return a string?

You could change your function to something like
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <string>
#include<iostream>

using namespace std;

string b();

int main()
{
    cout << b() << endl;
    return 0;
}

string b()
{
    return "need to show on console";
}
Last edited on Sep 19, 2017 at 12:56pm
Sep 19, 2017 at 3:21pm
i mean what is the diference between
cout<<b;
and
cout<<b();
Sep 19, 2017 at 4:23pm
b is a variable. (in this case the it is the name of a function, which is 'sort of' a variable in some sense of the word, at the compiler/ assembler level).
b() is a function call result.

printing b (which is a function) here is going to give the address of the function, I think.
b() is correct.
Last edited on Sep 19, 2017 at 4:26pm
Topic archived. No new replies allowed.