I'm new to C++. I was looking at the function tutorial on this site, and looked at this program:
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;
}
When i was fiddling around with the code, i took out the return in the function.
int addition (int a, int b)
{
int r= a + b;
}
int main ()
{
cout << "The result is " << addition (5,3);
return 0;
}
With multiple digits i still came to the same output on the screen with both programs.
So my question is:
1) Is it necessary to type in return? I think you would need it if you have more than one variable in the body of the function. But is it ok to leave it out if you have only one variable?
2) In the body of the function, is it better to write only return a + b; ?
There is no guarantee. By chance, on your system, the value you want happens to be left in the place the << operator goes looking. On other systems it will not happen. If you want to use a value returned from a function, you need to return the value.