Home > Enterprise >  Can the names of parameters in function definition be same as the name of arguments passed to it in
Can the names of parameters in function definition be same as the name of arguments passed to it in

Time:03-10

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?

CodePudding user response:

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.

  • Related