2

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?

Leonardo
  • 1,452
  • 3
  • 15
  • 26
  • Saves you from pressing 3 keys, though `int power(int, int);` would have saved you more. – Musa Nov 12 '12 at 03:47
  • 1
    @Musa Then couldn't you just place the source of the power() function in front of main() so as to then save a whopping 27 key presses? – Leonardo Nov 12 '12 at 03:48
  • Yes, you could move the definition ahead of its point of use. There are advantages to having a declaration and a definition; it gives an element of consistency checking. More typically, the function would be in a separate source file from the `main()` program, and a header file would contain the declaration, and both the file defining the function and the file containing the `main()` program — where the function is used — would include the header. The header provides a consistency check. – Jonathan Leffler Nov 12 '12 at 03:52

1 Answers1

4

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278