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.
A method with a void return type will work fine when you omit the return statement.
A value-returning function should include a return statement, containing an expression. If an expression is not given on a return statement in a function declared with a non- void return type, the compiler issues a warning message.
If the return statement does not have an associated expression, it returns the undefined value.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With