Search code examples
cpointerskernighan-and-ritchie

How does c compiler interpret declaring function and variable in the same statement?


I came across one of the declaration in K&R, where a function and a variable are declared together in the 'Pointers' chapter:

double atof(), *dp;

How does a C compiler handle above declaration?


Solution

  • The syntax for declarations (C17 6.7) is:

    declaration:
      declaration-specifiers init-declarator-list(opt) ;
    

    where one case of declaration-specifiers is type-specifier, in this case double.

    Digging further into the init-declarator-list gives init-declarator, optionally several separated by comma:

    init-declarator-list:
      init-declarator
      init-declarator-list , init-declarator
    

    init_declarator in turn gives declarator, which has the syntax (C17 6.7.6):

    declarator:
      pointer(opt) direct-declarator
    

    In the example, atof() and dp are direct-declarator, where dp has the optional pointer syntax.

    This means that atof() ends up a function returning double and *dp a pointer to double.

    (If you want to dig through the raw syntax like above, Annex A of the standard is helpful. No sane person remembers things like this without looking them up.)


    But there is really no reason to ponder awfully written code like this. The following is widely recognized as bad practice:

    • Writing function declarations anywhere else but as a line of its own, at file scope.
    • Writing function declarations that do not have prototype format. The correct prototype for atof in standard C 7.22.1.1 is double atof(const char *nptr);. Whereas double atof() means a function taking any parameter. This is obsolete style as per C17 6.11.6.
    • Writing multiple declarations at a single line. Don't write things like double d, *dp;, write double d; double* dp;. The former is known to cause bugs because of accidentally declaring the wrong type. As a bonus, if you always split the declarations, you don't have to ponder if it is more correct to write double* dp style or double *dp style.

    Summary: don't read obsolete programming books from the 1970s. The attempted K&R update to C90 was sloppily made and a lot of the 2nd edition of the book is not up to date with 1989 years changes. For example the obsolete style was already there in C90 6.9.4. So the book contains practice that was already flagged obsolete by the C standard in the year 1989! Plain horrible.