Search code examples
c++cfunction-prototypes

C/C++ need for local functions prototypes?


Is there any advantage on explicitly prototype local functions in C/C++, instead of defining the functions before use? By local I mean functions only used whithin their source file. An example is this:

#include "header.h"

static float times2(float x){
    return 2*x;
}

static float times6(float x){
    return times2(3*x);
}

int main(void){

    // Other stuff ...

    float y = times6(1);

    // Other stuff ...
}

Versus this:

#include "header.h"

// Local function prototypes
static float times2(float);
static float times6(float);

// Main
int main(void){

    // Other stuff ...

    float y = times6(1);

    // Other stuff ...
}

// Local functions definition
static float times2(float x){
    return 2*x;
}

static float times6(float x){
    return times2(3*x);
}

Personally I prefer to use the first option as there is less code to write and (for me) the file is easier to read, but now I wonder if there is any technical reason to prefer the second option.

EDIT: I added static to times2() and times6(), see @Gangadhar answer and comments following.


Solution

  • There are cases when you need to declare the function prototype beforehand, i.e. the compiler needs to know a functions prototype before you are able to use that function.

    Consider these functions that do nothing particularly useful:

    int foo(int x)
    {
        if(x < 1) return x;
        else return x + bar(x-1);
    }
    
    int bar(int x)
    {
        if(x < 3) return x;
        return x * foo(x-1);
    }
    

    If you try to compile this, the compiler gets mad at you:

    error: 'bar' was not declared in this scope

    You need to put the missing prototypes in front of the function using it:

    int bar(int);
    // as above unchanged
    

    This is the only case where the compiler requires you to put a function prototype before your functions. In all other cases it is perfectly legal to put prototypes anywhere as often as you'd like, so this is also legal:

    int foo(int);
    int bar(int);
    int foo(int);
    int bar(int);
    

    Though obviously redundant (please don't do that). Some people consider it good style to put a function prototype of every function within a file at the top of the file, because

    1. you don't have to care about cases in which the compiler requires you to do it anymore, and some people apparently cannot interpret the error message by the compiler (which I think is very concise), and
    2. you see on one view what functions are provided by the file and how they are called.

    But this is exactly that, a style discussion. I like to keep my code as short as possible, so I would only use the prototypes that are required by the compiler, but that's purely a matter of taste and convention. When in Rome, do as the Romans or something like that.