C++: Difference between int* and int& and int
Actually what I want to mention is the new type, reference,
introduced via c++, but here I just use int&
as an
example.
int
it is apperantly an integer type we are quite familiar with.
int*
This is a type of int pointer. Since it points at int, so it will
read 4 byte to represent an integer and return the first byte. (In C, we
do not take it as a type, it is something kinda like an address, and it
it presented as int *p
)
int&
int&
is a reference to a pointer. Literally it is
just a 'nickname' of an integer. int a; int& p = a;
p
can be used just like an integer with all operations.
So why reference is introduced?
A: if we do not use reference, there will be something wrong with passing values to function (still we can still solve it via pointer). For example, in a vector class, we have a function that will return a modifiable value of an entry. So we have to introduce reference.
Note: reference is just another name of its origianl
type, so it will not allocate a new memory space for it, thus an
reference without initilizatin is not permitted,
int& p; // error