Violapterin
Violapterin

Reputation: 347

Is it okay to duplicate function argument name when in implementation and in calling?

If I have

#include <iostream>
int fun(int,int);

int main(void)
{
   int foo=3;
   int bar=5;
   std::cout << fun(foo,bar);
}

int fun(int foo, int bar){ return foo+bar; }

Will there (possibly) be confusion (by either human or complier!) regarding conflicting names foo and bar, one in the function definition, one in main program body? So far I find the result all correct, but it is better to know the best practice. Indeed I often run out of imagination, and name the two occurrences (as in the example) to be the same.

(I have wondered this for years; this is so basic that I am sure someone must have asked before in the long history of SO, but I cannot find any by now. If duplicated, by all means let me know.)

Upvotes: 0

Views: 1085

Answers (1)

duong_dajgja
duong_dajgja

Reputation: 4276

To compiler, each variable is associated with a scope defined by the language standard then there must not exist any cases of mis-understanding. If in a case at which compilers cannot decide the scope of a variable then an ambiguous compiling error is raised.

Example: Same name, but different scope.

int x = 10;

void func() {
  // the definition of local x below hides global x in current scope
  int x = x; // local x is assigned value of global x
  x = 5; // local x is assigned 5, this does not affect global x
  printf("local x = %d\n", x);
}

int main() {
  func();

  printf("global x = %d\n", x);

  return 0;
}

To see how compilers can treat variables with the same name but different scope, read more at How does a C compiler differentiate a local and a global variable of the same name?

To human, it's called naming convention. You are free to use any valid names to name your variables but you are recommended to follow some consistent rules - that will make your code a lot more readable and maintainable.

Upvotes: 1

Related Questions