Home > Software engineering >  Returning a boolean literal from function as reference
Returning a boolean literal from function as reference

Time:04-01

I have encountered this code during trying to find a bug:

int x = 10; // for example

const bool& foo() {
    return x == 10;
}

int bar() {
    bool y = foo(); // error here
}

This code block causes a crash when compiled with gcc11.2, while it works correctly and sets y as true in Visual Studio 2019. Both compilers give a warning about returning reference to local variable. I would like to know whether this behaviour is an UB or not. (We fixed this bug by changing bool& to bool)

Edit: I forgot to put const before bool&, sorry about that.

CodePudding user response:

Have you tried changing the compiler version? The code shouldn't even compile because it binds a reference to a temporary value. Below output of g 7.5 g 7.5.0

error: cannot bind non-const lvalue reference of type ‘bool&’ to an rvalue of type ‘bool’

A not const reference does not bind with temporary values. The compilation problem can be bypassed with a temporary reference

const bool& foo() {
    return x == 10;
}

but the undefined behavior would remain as it is linked to a temporary value.

CodePudding user response:

This is undefined behaviour as you are trying to return a reference on a value whose scope is destroyed once you exit the function.

CodePudding user response:

x == 10 is a rvalue not an lvalue, it has not address and you can reference it. If it works under VS 2019 it means that the compiler must surely optimize the code and inline the function or something like that. In debug mode it should not work.

  • Related