简体   繁体   中英

Can the names of parameters in function definition be same as the name of arguments passed to it in the function call in C++?

Suppose we have a function as given below:

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

Now, I call the above function by passing the arguments having the same name as the parameters in the add function.

int num1 = 10;
int num2 = 10;

int result = add(num1, num2) 

Is it correct to do so? The code compiles correctly But I am not sure whether I am doing the correct thing or not?

Yes, the names of the variables you pass in a function call can be the same as the names of the parameters in the function definition. The scope of the function parameters begins and ends in the function block, so the compiler can keep the two (or more) variables defined at different scopes separate, even when they have the same name.

You can call your function by passing variables with the same name ( add(num1, num2) ), different names ( add(x, y) ), or no names at all ( add(3, 4) ).

See the Function parameter scope section in the C++ Scope reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM