Reputation: 49
If I have a function which takes a pointer to an integer, and I pass a reference to an integer variable from my main, is this call by value or call by reference? Sample code:
#include <iostream>
using namespace std;
void fun(int *a){
//Code block
}
int main(){
int a = 5;
fun(&a);
return 0;
}
In the above code, is the call to function fun a call by value or call by reference?
Upvotes: 3
Views: 11149
Reputation: 1
It is call by reference as you are passing reference the address reference to your variable so,
inside function
*a = 100;
changes the value of a in caller function as the content at that address has been changed.
But address is passed by value so
a = NULL;
will not change a, as a still be pointing to same address.
Upvotes: -1
Reputation: 21351
Your call is a pass by value, but of type int*
not of argument type int
. This means that a copy of the pointer is made and passed to the function. You can change the value of what it points to but not of the pointer.
So if your function is like this
void fun(int *a)
{
*a = 10;
}
and you call from main
like this
int main() {
int b = 1;
fun(&b);
// now b = 10;
return 0;
}
you could modify the value of b
by passing a pointer to it to your function.
The same effect would be if you did the following - which is passing by reference
void fun2(int& a)
{
a = 5;
}
int main()
{
int b = 10;
fun2(b);
// now b = 5;
return 0;
}
Now consider a third function that takes an integer argument by value
void fun3(int a)
{
a = 10;
}
int main()
{
int b = 1;
fun3(b);
// b is still 1 now!
return 0;
}
With pass by value, fun3
changes the copy of the argument passed to it, not the variable b
in the scope of main.
Passing by (non-const) reference or pointer allows the modification of the argument that is passed to it. Passing by value or const reference will not allow the argument passed to it to be changed.
Upvotes: 5
Reputation: 918
You are passing by value the address where a is located.
So when in your void called fun you type *a, you're accessing the value of a.
But as I've said, you're passing by value an int pointer to a.
Upvotes: 1
Reputation: 385174
You're passing a pointer to a
, by value.
Depending on which level of abstraction you are speaking, you could say that you are therefore passing a
by pointer, or passing a
by "handle". In broader terms, "passing a
by reference" would not be strictly incorrect, but it is incorrect in C++ because "reference" means something specific in C++. You have no C++ references in this code.
Upvotes: 1