简体   繁体   中英

C++ function input argument by reference vs by pointer

I am new to C++ and have done only MATLAB earlier.

My Q is about the input argument of the following functions, which call variables by value,reference and pointer.

void SwapbyValue (int a, int b){
// Usual swapping code
}

void SwapbyRef (int &a, int &b){
// Usual swapping code
}

void SwapbyPoint(int *a,int *b){
//Usual swapping code
} 

Since my Q isn't about how the above functions work but rather about how I call them, I've left out the code. So, I understand we call the above functions by typing SwapbyRef (i1,i2),SwapbyRef (i1,i2) and SwapbyPoint(&i1,&i2) when i1 and 12 are int.

That confuses me the life out of me. Okay, I get that the first function takes in values and makes sense. But in the second one, calling by just i1 and i2 doesn't make sense as when the function is defined, we set its input as &a and not just a but it still runs. Again in the third, we set the input argument as a pointer ie *a but we're passing an address &a (like 0x7956a69314d8) when we call it.

Why does it run when we pass the wrong kind of input to the function? For example,a Matlab analogy,it looks like passing a char to a int function. Help!

int &a is a reference to an int, meaning, it will accept all int variables that already exist. What you cannot do is for example SwapbyRef(4, 5) using SwapbyRef (int &a, int &b) , because 4 and 5 are temporary ints that do not exist somewhere in memory as variables.

Btw, you should probably just look up what a reference in c++ is. That would help you most, I think.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM