C++ return value without return statement

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;
}

Leave a Comment