When pass a variable to a function, why the function only gets a copy/duplicate of the variable?
int n=1;
void foo(int i)
{
i++;
}
As we all know, the function foo() can't change the value of n
by using foo(n).
Of course we can pass the address of the variable to make some change to the parameter variable.
But don't you think that is a little bit inconvenient?
Why c/c++ is designed to only give a duplicate to the function instead of directly give the "real" variable itself to the function?
What't the pro/benefit of this paradigm?
Update:
I have read @paxdiablo's answer. I think his "encapsulation, modularity and localisation of effect" explanation is good.
But in my way, it can also preserve the parameter argument's value as well. It can also realize encapsulation. By this way:(assume the function can directly get the "real" variable instead of a duplicate by default )
void foo(int n)
{
int temp=n;
//Do something to temp...
}
And in my way, the complicated mechanism,such as "pass by reference" or pointer can be eliminated when you do want to change the value of parameters passed in. That's the benifit.
After a time of thought. I realise the reason why c/c++ isn't designed as I proposed is just because of the INCONVINIENCE of my way!
In my way, if a function has a long list of variables, it would to terrible. What I thougth is the more convenient way is infact inconvenient:
You must write like this:
void foo(int a,int b,double c,float d,char s...)
{
int temp1=a;
int temp2=b;
double temp3=c;
float temp4=d;
char temp5=s;
...
//Do something to temp{1,2,3,4,5....}
}
So the designers of c/c++ introduce complex mechanism to trade off with convenience.
Am I right?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…