Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

References as function arguments?

I have a trouble with references. Consider this code:

void pseudo_increase(int a){a++;}  
int main(){  
    int a = 0;
    //..
    pseudo_increase(a);
    //..
}

Here, the value of variable a will not increase as a clone or copy of it is passed and not variable itself.
Now let us consider an another example:

void true_increase(int& a){a++;}
int main(){  
    int a = 0;
    //..
    true_increase(a);
    //..
}

Here it is said value of a will increase - but why?

When true_increase(a) is called, a copy of a will be passed. It will be a different variable. Hence &a will be different from true address of a. So how is the value of a increased?

Correct me where I am wrong.

like image 871
T.J. Avatar asked Jan 19 '12 05:01

T.J.


People also ask

Are Python function arguments passed by reference?

All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.

What happens when we pass arguments in a function by reference?

Passing by by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function. In C, the corresponding parameter in the called function must be declared as a pointer type.

How function can be called by using reference?

While calling a function, instead of passing the values of variables, we pass address of variables(location of variables) to the function known as “Call By References. In this method, the value of each variable in calling function is copied into corresponding dummy variables of the called function.

How are arguments passed by value or by reference in functions?

When you pass an argument by reference, you pass a pointer to the value in memory. The function operates on the argument. When a function changes the value of an argument passed by reference, the original value changes. When you pass an argument by value, you pass a copy of the value in memory.


2 Answers

Consider the following example:

int a = 1;
int &b = a;
b = 2; // this will set a to 2
printf("a = %d\n", a); //output: a = 2

Here b can be treated like an alias for a. Whatever you assign to b, will be assigned to a as well (because b is a reference to a). Passing a parameter by reference is no different:

void foo(int &b)
{
   b = 2;
}

int main()
{
    int a = 1;
    foo(a);
    printf("a = %d\n", a); //output: a = 2
    return 0;
}
like image 76
B Faley Avatar answered Oct 06 '22 08:10

B Faley


When true_increase(a) is called , copy of 'a' will be passed

That's where you're wrong. A reference to a will be made. That's what the & is for next to the parameter type. Any operation that happens to a reference is applied to the referent.

like image 5
Benjamin Lindley Avatar answered Oct 06 '22 07:10

Benjamin Lindley