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

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


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.