Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reasons for declaring a function immediately before defining?

So in this another old huge C++ codebase I'm spotting this style quite often:

// ...

void FooBar::Eggs(int spam);
void FooBar::Eggs(int spam) {
    // implementation here
    // ...
}

In general, I do understand what's the point of forward declaring a function in C++, however I can't find any justification for this kind of duplication. Is there any reason to not eliminate it?

like image 813
ulidtko Avatar asked May 20 '26 05:05

ulidtko


1 Answers

If this is a codebase that predates standard C, it is possible that this code originally looked something like this:

#ifdef PROTOTYPES
void FooBar_Eggs(int spam);
#endif
FooBar_Eggs(spam)
     int spam;
{
    ...;
}

1990s-era C compilers, even if they supported prototypes, would not deduce a prototype from an "old-style" function definition for the benefit of code below it in the same file, so you would pretty regularly see this sort of construct in code intended to compile both with standard-compliant and legacy compilers.

Now imagine that at some point between then and now someone mechanically converted all the old-style function definitions to prototyped definitions, and someone else mechanically converted the C to C++, and the result might well look like what you have.

The leading declaration serves no purpose anymore and can safely be removed.

like image 57
zwol Avatar answered May 22 '26 19:05

zwol