What is the purpose in declaring a function with different named arguments than the function itself uses?

StackOverflow https://stackoverflow.com/questions/13338118

  •  28-11-2021
  •  | 
  •  

Question

Perhaps this is just for showing. While reading K&R, the beginning of 1.7 Functions shows an example of a power function. The second line of code declares int power(int m, int n);

Why is the first argument, n, named differently than the first argument, base, in the source of the function:

int power(int base, int n)
{
   ...
}

Is this simply to show that the names do not need to be the same? And should this practice be avoided? Why or why not?

Was it helpful?

Solution

The types, and not the names, are what is important in the prototyped declaration. Some people omit the parameter names in the declaration; some use more descriptive names in the declaration (because people may need to read them in the header) than in the function definition. The opposite appears to be the case here; the name in the definition is more meaningful than in the declaration.

It is purely stylistic. I normally reckon to use the same names in declaration and definition, but sometimes the name needed for the definition (to explain the argument) is too verbose for comfortable use in the function definition.

See Stroustrup's "Design and Evolution of C++" for a discussion of why named parameters are not a part of C++. Yes, that's C++, but the arguments there (primarily unnecessary coupling between declaration and definition) apply to C too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top