i want to know whether function(int &n) and function(int* n) will do same job or not? and also how can we pass the value of n directly in the first one?
Basics of pointer
Hello @sktg99,
-
Yes, In both the cases changes made in the value of n inside the function will be reflected back in the main function.
-
I didn’t understand your second question. Can you explain with an example?
take my first case, how can we use that function, should it take a value which is address of ‘n’ or just simply ‘n’ ?
for example, i have n=5, now i want to pass it to the function, so which is right, function(&n) or function(n)? if function(n) is correct(which is actually correct) then why is it happening because there are two different declarations but used in similar way
Hello @sktg99,
What is happening here is that you are creating a reference variable.
Now, what is a reference variable?
A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable.
Example:
//Initializing a
int a=2;
//Creating a reference to a
int &b=a;
a=a+1;
cout<<a<<" “<<b;
//OUTPUT: 3 3
b=b+1;
cout<<a<<” "<<b;
//OUTPUT: 4 4
You have friends with multiple names(Example: Viren and Virender). It’s the same concept.
If you would thank Viren then you are automatically thanking Virender as both are the same person.
Now, let’s understand in terms of function:
//Function call
function(a)
//Function Definition
void function(int &b){ }
It is equivalent to:
int &b=a;
That is why it is called call by reference method.
In the case of pointers:
//Function call
function(&a)
//Function Definition
void function(int *b){ }
Equivalent expression:
int *b=&a;
Hope, this would help.
Give a like, if you are satisfied.
but i think & is used to get address of a variable, or reference of a variable?
Hey @sktg99,
It can be for two ways:
-
To get address:
int a;
cout<<&a; -
To create a reference variable:
int a;
int &b=a;
There is a difference in representation and usage of this operator.
You can use single operator for multiple purposes.
Examples:
- operator
- To create a pointer variable.
- To multiple two operands.
Compiler would differentiate between the two by the position where it is used and the tokens written around it.
Hope, this would help.
okay thanks it helped!