-3

I got 3 questions.

1.what is the difference between the flowing 2 codes?

//why no errors during compiling as flowing
const int& get3() {
    return 3;
}

and

//get a compiler error, says: 'return': cannot convert from 'int' to 'int &'
//and that's understandable
int& get3() {
    return 3;
}

2.Why the first one is OK to compile?

3.And when i run the first one, i got the strange result:

error image

That's why?

I'll appreciate it very much if anyone can give me some tips.

Kang Yin
  • 11
  • 2

2 Answers2

3

With int& get3() you can do, for example, get3() = 5.

This will set the value of the variable whose reference is returned by function get3 to 5.

Since 3 is a constant value with no address to be used as reference, you get a compilation error.

Such functions typically return a reference to a class member variable.

barak manos
  • 29,648
  • 10
  • 62
  • 114
1
  1. The first one is actually not OK, even though it compiles. It returns a reference to a local temporary which is undefined behavior (because that temporary gets destroyed after function exits, so you get a dangling reference). The compiler should have already told you about this by issuing a warning.

    Basically it's equivalent to the following:

    const int& get3() {
        const int& x = 3; // bind const reference to a temporary, OK
        return x; // return a reference to a temporary, UB
    }
    

    And this also answers your third question:

  2. Because you have UB in your code.

I'd also recommend to read this brilliant answer.

Community
  • 1
  • 1
Anton Savin
  • 40,838
  • 8
  • 54
  • 90
  • Thanks, I understand what you say in "2." and why the second function got a compiler error. Sorry for not describing my question clear, I'm wondering why the first function returned "const int&" complies by return a constant int 3? – Kang Yin Feb 23 '16 at 07:49
  • 1
    @KangYin again, this particular code contains undefined behavior and the function can return anything, including `3`. – Anton Savin Feb 23 '16 at 07:51