#include <iostream>
usingnamespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return (r);
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
}
And i when i tried to remove the return(r); ,the output still the same.
So what is return(r) for in the code above?
Functions that have non-void return type shall return an object. The compiler must issue an error when you removed the return statement. Without the return statement the function has undefined behaviour.
I can guess why your code without the return statement worked, The compiler placed the value of the expression a + b in register EAX. In main in this statement
z = addition (5,3);
the compiler used the same register EAX to assign the result of the function execution to variable z.
It worked only due to the function is very simple and the register EAX was not overwritten before exiting the function.
@vlad from moscow
so you're saying that because the function is named addition, and because the EAX also know addition , it return the value by itself?
@Techno01
did you tried to compile it then execute it ?
what compile do you work with?
@vlad from moscow
so you're saying that because the function is named addition, and because the EAX also know addition , it return the value by itself?
it seems when the control reached the closing brace of the function register EAX contained the result of the calculation. So when the control was returned to main the object code used register EAX to assign the return value to variable z. But it is a fortune that EAX contained the result. In general the function behaviour is undefined.
I can see that its hard for you to understand some of the "why does it work if it actually should not"..
To easy you.. just type the return.
It was probably a lucky accident that it worked out for you, but you should always write a return statement.
Even if you actually don't want to return something, always use return 0;.
Else you will have big problems later on in programming.