how does the ampersand(&) sign work in c++? [duplicate]

The & has more the one meanings:

1) take the address of a variable

int x;
void* p = &x;
//p will now point to x, as &x is the address of x

2) pass an argument by reference to a function

void foo(CDummy& x);
//you pass x by reference
//if you modify x inside the function, the change will be applied to the original variable
//a copy is not created for x, the original one is used
//this is preffered for passing large objects
//to prevent changes, pass by const reference:
void fooconst(const CDummy& x);

3) declare a reference variable

int k = 0;
int& r = k;
//r is a reference to k
r = 3;
assert( k == 3 );

4) bitwise and operator

int a = 3 & 1; // a = 1

n) others???

Leave a Comment