Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 888
Simplicity Avatar asked Jan 27 '11 11:01

Simplicity


People also ask

Can a method omit a return statement?

A method with a void return type will work fine when you omit the return statement.

Should a function contains return statement if it does not return a value?

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.

What happens if a return statement not accompanied by an expression?

If the return statement does not have an associated expression, it returns the undefined value.


1 Answers

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;
}
like image 98
Fred Foo Avatar answered Oct 25 '22 12:10

Fred Foo