C++ return value without return statement
When I ran this program:
#include <iostream>
int sqr(int&);
int main()
{
int a=5;
std::cout<<"Square of (5) is: "<< sqr(a) <<std::endl;
std::cout<<"After pass, (a) is: "<< a <<std::endl;
return 0;
}
int sqr(int &x)
{
x= x*x;
}
I got the following output:
Square of (5) is: 2280716
After pass, (a) is: 25
What is 2280716
? And, how can I get a value returned to sqr(a)
while there is no return
statement in the function int sqr(int &x)
?
Thanks.
Strictly, this causes undefined behavior. In practice, since sqr
has return type int
, it will always return something, even if no return
statement is present. That something can be any int
value.
Add a return
statement and turn on warnings in your compiler (g++ -Wall
, for instance).
int sqr(int &x)
{
return x = x*x;
}
That's some garbage that will depend on a handful of factors. Likely that's the value stored in memory where the function would put the result if it had a return
statement. That memory is left untoched and then read by the caller.
Don't think of it too much - just add a return
statement.
Your function sqr()
has no return statement. The function has undefined behavior concerning return value. Your first output shows this return value.
The compiler should show a diagnostic though.
try this:
int sqr(int x)
{
return x*x;
}
You are trying to print the return value of sqr(int &x), which is garbage value in this case. But not returning the proper X*X. try returning valid X*X from sqe
int sqr(int &x) { x= x*x; return x;}