76

What is the meaning of the following line? Why is this allowed as 0 is an r-value and not a variable name? What is the significance of const in this statement?

const int &x = 0;
DeiDei
  • 10,205
  • 6
  • 55
  • 80
user3112666
  • 1,689
  • 1
  • 12
  • 12

1 Answers1

71

A non-const reference cannot point to a literal. You cannot bind a literal to a reference to non-const (because modifying the value of a literal is not an operation that makes sense) and only l-values can be bound to references to non-const. You can however bind a literal to a reference to const.

The "const" is important. In this case, a temporary variable is created for this purpose and it's usually created on stack.

Zoe
  • 27,060
  • 21
  • 118
  • 148
user3112666
  • 1,689
  • 1
  • 12
  • 12
  • 3
    Are you sure that the “temporary variable” is created on the stack? I would have expected that `x` is pointing to some area in the data segment. Similar how string literals work. If `x` points onto the stack, the reference could become invalid too early. For example, if you pass the reference as a pointer to some static variable and leave the method. Besides that, if every call of the method would create a new “temporary variable”, I think we wouldn't need to use `const`. I think `const` is necessary because the memory area is reused between function calls. – JojOatXGME Nov 29 '21 at 01:30