0

If I write:

int a = 5;
int& b = a;

in c++, (I have to be careful in how I ask this), can a and b be used completely interchangeably? Or does a have some properties, restrictions, semantics, etc. that b doesn't, or vice versa?

I know that the templating machanism will detect the difference between a plain type and a reference type. But, is there any other situation?

vallentin
  • 23,478
  • 6
  • 59
  • 81
Henry Bigelow
  • 313
  • 1
  • 10
  • They're identical. Check with `typeid(a) == typeid(b)`. – tadman Dec 02 '20 at 00:44
  • Well, yes and no, depending on context. Best consult a tutorial (e.g. https://www.cprogramming.com/tutorial/references.html), as those are more suited to explain the basics than an SO answer. – Haatschii Dec 02 '20 at 00:48
  • And a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) usually beats a tutorial. – user4581301 Dec 02 '20 at 00:51
  • 1
    The only big important difference is when the `a` goes out of scope, `b` (if still around) will be a dangling reference. A small difference *may* be performance, but before stressing about reference overhead performance impact: **profile** your optimized build — optimizers can do amazing things, and may eliminate the reference machinery. – Eljay Dec 02 '20 at 02:31

1 Answers1

0

A reference is just an alias for the variable it is referencing. Once a reference is bound, anything you do to the reference is applied to the referenced variable. So yes, for all intents and purposes, they are interchangable.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770