Write your question here.
I am new with pointer, and i don't really understand how it works in function prototype, hen i do this in the function prototype and the function, I can pass the value by reference:
void swap(int*,int*);
but okay with both
1 2 3 4 5
void swap(int a, int b){
int temp=a;
a=b;
b=temp;
}
and
1 2 3 4 5
void swap(int& a, int& b){
int temp=a;
a=b;
b=temp;
}
which one is the correct one?Why and how does this work??
I am new with pointer, and i don't really understand how it works in function prototype, hen i do this in the function prototype and the function, I can pass the value by reference:
void swap(int*,int*);
There is no "passing a value by reference" here. More accurately, you are passing the address of two variables by value in the form of pointers.
which one is the correct one?Why and how does this work??
The latter. Look up "pass by value" and "pass by reference."
The prototype must match the definition with regards to the type(s) of parameters. If the prototype doesn't match the definition, it refers to a different function.
In this function the value of a and b will change, but in the main function the value will not changeļ¼ because a and b are local variables, so they can't affect the variable of main.
1 2 3 4 5 6 7 8
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
in this function a and b are like another name to the variables of main function. they have the same address, that's why the value can change.
1 2 3 4 5 6
void swap2(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
in this function a and b are pointing to the variable of main function, so the value will change.
1 2 3 4 5 6
void swap3(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}