55

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
  • 9,680
  • 6
  • 51
  • 75
user3112666
  • 1,331
  • 1
  • 10
  • 12

1 Answers1

59

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 stands with Ukraine
  • 25,310
  • 18
  • 114
  • 149
user3112666
  • 1,331
  • 1
  • 10
  • 12
  • 1
    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
  • @JojOatXGME maybe vote on reopen this question - and give your own answer – Kamil Kiełczewski Jan 05 '22 at 23:02