cscopefunction-callfunction-declarationfunction-prototypes

Declaring a function prototype in a brace


In 'The C Programming Language(2nd)' 71~72p,

Second, and just as important, the calling routine must know that atof returns a non-int value. One way to ensure this is to declare atof explicitly in the calling routine.

And the code right under the paragraph including above part.

#include <stdio.h>

#define MAXLINE 100

/* rudimentary calculator */
main()
{
    double sum, atof(char []);
    char line[MAXLINE];
    int getline(char line[], int max);

    sum = 0;
    while (getline(line, MAXLINE) > 0)
        printf("\t%g\n", sum += atof(line));
    return 0;
}

A function prototype is declared at top in general. But why the function prototype double atof(char[]) is declared in the main()? I've never seen like that although I am a novice.


Solution

  • For starters in early versions of C you may call a function without declaring it before the function call. In this case by default it was supposed that the function has the return type int.

    Pay attention to that in general a function declaration does not necessary provide the function prototype.

    Compare these two function declarations

    int f();
    

    and

    int f( void );
    

    The first function declaration means that you can say nothing about the number and types of the function parameters.

    The second declaration is indeed a function prototype that means that the function does not have parameters.

    So if within a program there is a function call and you are using an old compiler then it is assumed that the function has the return type int.

    To say the compiler that the function has a different return type you need to declare the function before the function call.

    You may declare a function in the file scope or in a block scope in which the function is called.

    This function declaration

    double sum, atof(char []);
    ^^^^^^      ^^^^^^^^^^^^^^
    

    that at the same time is the function prototype is placed in the outer block scope of main though you could place it before main. In the last case the function prototype would be visible for the entire module.

    It would be more correctly to declare the function like

    double atof( const char [] );
    

    because usually such a function does not change the passed string as an argument.

    Also bear in mind that there is a standard C function with the same name declared in the header <stdlib.h>.

    double atof(const char *nptr);