When a variable is passed to a function, why does the function only get a copy / duplicate of the variable?
int n=1; void foo(int i) { i++; }
As we all know, the function foo () cannot change the value of n
with foo (n).
Of course, we can pass the address of the variable to make some changes to the parameter variable.
But don't you think this is a little uncomfortable?
Why is c / C ++ intended only for duplicating a function, and not for directly providing a "real" function variable?
What is the use of this paradigm?
Update:
I read @paxdiablo's answer. I think his explanation of "encapsulation, modularization and localization of the effect" is good. But in my way, it can also save the value of the parameter. It can also implement encapsulation. Thus: (suppose the function can directly get the "real" variable instead of the default duplicate)
void foo(int n) { int temp=n;
And in my opinion, a complex mechanism, such as "pass by reference" or a pointer, can be deleted when you want to change the value of the passed parameters. It's profitable.
Over time. I understand the reason why c / C ++ is not designed, as I suggested, simply because of the CONTINUITY of my path!
In my opinion, if a function has a long list of variables, it will be terrible. What I'm doing in a more convenient way is inconvenient:
You should 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; ...
Thus, c / C ++ developers introduce a sophisticated mechanism to compromise convenience.
I'm right?