I assumed that one of the most used system functions (ls) of one of the most famous OSs (linux) written by one of the most authoritative programmers (Richard Stallman) could be an example of really well written code.
So, being it open source, I decided to have a look at the code (see e.g. here). There I found several functions defined after the main(), hence after their call, which I expected to be quite uncommon.
Will any experienced C programmer comment on this?
There’s absolutely nothing wrong with what Stallman did here.
The C language permits the forward declaration of a function that will be defined afterwards.
This has many advantages, and should not be considered as bad behavior, but rather very good behavior.
Advantages (not exhaustive):
– give the programmer a vision of the API exposed by the C code in a quick look, without having to look at all the code
– permits the use of header files, where you declare a function that will be defined later on in the compilation process. So that you don’t have to define your function every time you use it..
In the case of this
lsimplementation, he simply pre-declared the functions that he’ll use in themain(), but if you look carefully, the main function is the first one to appear.This is most probably for the sake of readability, so that you don’t have to scroll all the way down to reach the entry point of the program.
Note that the vocabulary is important here:
– function declaration means: just tells the compiler that, somewhere in your code, a function with the same name will be defined.
– function definition : the actual function implementation
Edit: after looking more carefully to the code, you can see that Stallman didn’t forward-declare all his functions. He has also a rather strange manner of defining functions. I attribute this to the oldness of the code, which is dated of 1985, when the C compiler was not as well defined as today.
It must have permitted this kind of function usage before being declared or defined.
Last but not least, the recent version of
lssource code can be found here: http://coreutils.sourcearchive.com/documentation/7.4/ls_8c-source.html ,with much more C99-compliant coding than the ’85 (Back-to-the-Future) version.