Reputation: 107
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!
Upvotes: 1
Views: 145
Reputation: 122298
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.
Upvotes: 2
Reputation: 1062
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.
Upvotes: 0