Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do reference variables need to be initialized at definition?

I've tried searching around for the answer, but no luck so far. My question is - why must reference variables need to be initialized when they are defined? Is it a technical reason, or is it just something the standard doesn't allow?

Take this code for example:

int number = 42;
int& numberRef;
numberRef = number;

Above isn't allowed, but the code below is:

int number = 42;
int& numberRef = number;

Why can't the compiler treat an uninitialized reference variable like an uninitialized pointer? Is there something I'm missing here?

like image 411
Greg M Avatar asked Feb 08 '26 03:02

Greg M


1 Answers

If a reference is uninitialized, there is no way to initialize it, since any attempt to assign to a reference always assigns to its referent.

int& numberRef;     // pretend this is allowed
numberRef = number; // copies number into some random memory location
like image 160
Brian Bi Avatar answered Feb 09 '26 17:02

Brian Bi