0

Why it doesn't runs..pls explain ?

#include <iostream> using namespace std; int addNumbers(int x, int y) { int result = x + y; return result; } int main() { int addNumbers(50, 25); cout<<addNumbers; }

1st Dec 2016, 7:58 PM
Black Temple
Black Temple - avatar
7 Answers
+ 4
firstly you wrote int addNumbers(50,25) which is incorrect because your function will return a value which should be stored in an int variable rather than declaring function it self as a variable. So write as int res = addNumbers(50,25); now to print the result generated by your function just print the variable res as cout << res; instead of these two lines you can also do cout << addNumbers(50,25); this will also display the same result.
1st Dec 2016, 8:14 PM
Mohammed Maaz
Mohammed Maaz - avatar
+ 1
I am so new to all this fun. still i will try. i think "cout<<addNumbers" is the faulty line. that's a function and not a variable. now in the previous line you are not storing the result. it is being recalculated at this line but without arguments. you could introduce a local variable here to store the result in the previous line.
1st Dec 2016, 8:12 PM
Goutam Rudra
Goutam Rudra - avatar
+ 1
thank-you, i understand but could you please write the correct code ? it will clear my doubts.
1st Dec 2016, 8:15 PM
Black Temple
Black Temple - avatar
+ 1
thank-you. but can you explain why "cout<<addNumbers(50,25) ". doesn't needs a variable to print the output? is it not same as cout<<addNumbers; ?
1st Dec 2016, 8:19 PM
Black Temple
Black Temple - avatar
+ 1
"is it not same as cout<<addNumbers; ?" not really. you are calling the function and not any variable. hence it is being evaluated when this statement is being executed. when you call a variable, the value stored in it is given to cout.
1st Dec 2016, 8:23 PM
Goutam Rudra
Goutam Rudra - avatar
+ 1
cout << addNumbets(50,25) dosen't need a variable because you are just providing the function's return value to cout. So it displays that value to the console window. just like you can do cout << 75, so actually addNumbers(50,25) here is returning 75 which can be used with cout without the need of a variable. secondly it's not the same as cout << addNumbers. instead you will get an error doing this, because addNumbers is a function so it should be called with it's paranthese just like addNumbers(). Even this is not enough because you have to give it the two required arguments otherwise you will get an error message of "too few arguments". So cout << addNumbers; is actually an error generating code and nothing else.
1st Dec 2016, 8:31 PM
Mohammed Maaz
Mohammed Maaz - avatar
0
thank you so much people. Doubts don't let you breathe. I can now move on.
1st Dec 2016, 8:35 PM
Black Temple
Black Temple - avatar