函数参数的名称是否可以与调用函数时使用的变量相同?

huangapple go评论139阅读模式
英文:

Is it valid for function parameter's names to be the same as the variables used in the call to the function?

问题

在程序中,可以使用与函数参数名称相同的变量名来调用函数,这是程序上没有问题的。例如:

int num1 = 10;
int num2 = 10;

int result = add(num1, num2);

但是,为了提高代码的可读性和可维护性,通常建议使用不同的变量名来调用函数,以避免混淆。这样可以更清晰地表达变量的用途和含义。例如:

int input1 = 10;
int input2 = 10;

int sum = add(input1, input2);
英文:

Say I have a function:

int add(int num1, int num2) { 
    num1 += num2;
    return num1;
}

is it programatically correct to call the function with variable(s) which contain the same name(s) as the function's parameter's names?

example:

int num1 = 10;
int num2 = 10;

int result = add(num1, num2) 

Or is it programatically correct to use different names for the function call's variables/function parameters.

答案1

得分: 6

是的。这些变量位于不同的作用域中,因此是完全有效的。请参阅名称查找作用域

英文:

Yes. Those variables are in different scopes, therefore it is perfectly valid. See Name lookup and Scope:

> Each name that appears in a C++ program is only valid in some possibly
> discontiguous portion of the source code called its scope.

huangapple
  • 本文由 发表于 2020年1月6日 21:18:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612853.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定