What this code does is user enters a number and the console displays "the number entered is (what is entered)".
When the code is executed, the sub function is executed twice. Why is the sub function executed again even though it is placed in "cout<<"? I only wanted the return value of the sub function. Thanks for the Help.
#include <iostream>
int sub()
{
using namespace std;
int y;
cin>> y;
return y;
}
int main()
{
using namespace std;
sub();
cout<< "the number entered is "<< sub()<< endl;
system("PAUSE");
return 0;
}
cout<< "the number entered is "<< sub()<< endl;
system("PAUSE");
return 0;
}
Edit: You can either remove the first instance (which won't give you the result you likely desire) or you can assign the return value from the function to it's own variable, like so:
1 2
int a = sub();
cout << "the number entered is " << a << endl;
Thanks alot Volatile Pulse. I added "int a = sub();". Strangely enough, declaring sub() as a variable also causes the function to run. I have deleted "sub();" so that it run only once.
My new code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
int sub()
{
usingnamespace std;
int y;
cin>> y;
return y;
}
int main()
{
usingnamespace std;
int a =sub();
cout<< "the number entered is "<< a<< endl;
system("PAUSE");
return 0;
}
It works but I find it strange why int a =sub();
will cause sub() to be called.
Because you're specifying that you want to initialize the value of a to the return value of sub. In order for the computer to figure out what the value of sub is, it must call sub first. You typed sub so that it'll return the value of y (let's say it was 10) so then that function effectively equals 10. Since a has to equal the right side, it's now assigned the value of 10 as well.