What does int & mean

It returns a reference to an int. References are similar to pointers but with some important distinctions. I’d recommend you read up on the differences between pointers, references, objects and primitive data types.

“Effective C++” and “More Effective C++” (both by Scott Meyers) have some good descriptions of the differences and when to use pointers vs references.

EDIT: There are a number of answers saying things along the lines of “references are just syntactic sugar for easier handling of pointers”. They most certainly are not.

Consider the following code:

int a = 3;
int b = 4;
int* pointerToA = &a;
int* pointerToB = &b;
int* p = pointerToA;
p = pointerToB;
printf("%d %d %d\n", a, b, *p); // Prints 3 4 4
int& referenceToA = a;
int& referenceToB = b;
int& r = referenceToA;
r = referenceToB;
printf("%d %d %d\n", a, b, r); // Prints 4 4 4

The line p = pointerToB changes the value of p, i.e. it now points to a different piece of memory.

r = referenceToB does something completely different: it assigns the value of b to where the value of a used to be. It does not change r at all. r is still a reference to the same piece of memory.

The difference is subtle but very important.

If you still think that references are just syntactic sugar for pointer handling then please read Scott Meyers’ books. He can explain the difference much better than I can.

Leave a Comment