简体   繁体   中英

Declarations vs. Definitions at the top of your program (Best Practice)

Using a function declaration at the top of your function, then later defining it under main seems a bit redundant. Considering the practices of DRY, is standard practice in the C++ community to simply declare the function fully at the top (or even just define in a seperate functions.cpp file, with declarations in the header.hpp file), rather than declare then later define?

I realize that all ways would produce the same result, but I would like to hone in on my formatting skills, and eliminate redundancy. Why declare then later define as opposed to just defining at the top before main? Perhaps this is a tabs vs. spaces type of debate, but maybe thats all I need to know lol

Thanks!

There are cases where you have no choice other than first providing a declaration and then the definition. For example when there is mutual dependency:

int bar(int x);

int foo(int x) {
    if (x == 1) return bar(x);
    return x;
}
int bar(int x) {
    if (x==0) return foo(x);
    return x;
}

Seperating declaration and definition is not considered a violation of DRY or as redundant. Probably the most common is to have declarations in headers and definitions in source files.

There may be some cases that you have to provide function signature in advance, and its implementation only later at some point. The best example is the cyclic dependency of functions, so one needs to be defined before the other one, making a closed loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM