I'm learning a little C over the holiday weekend, and I started to look at other programs written in C. I ended up looking at GNU Netcat, thinking it would be a good example.
I was a bit shocked to see a 600 line main()
function. Is this normal? If it is normal is this considered good C coding practices?
There's no requirement for main to be of any length whatsoever, other than coding standards. main is a function as any other, and as such it's complexity should be below 10 (or whatever your coding standards say). That's it, anything else is rather argumentative. main shouldn't be short.
Smaller must be better The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that. Functions should not be 100 lines long. Functions should hardly ever be 20 lines long.
No. It's non-standard. The standard prototype of main is int main() with the optional command line arguments argc and argv . The int returned by main() is a way for a program to return a value to the system that invokes it.
The return value for main is used to indicate how the program exited. If the program execution was normal, a 0 return value is used. Abnormal termination(errors, invalid inputs, segmentation faults, etc.) is usually terminated by a non-zero return.
There's a quote of an American President (Lincoln?) who was asked how long a man's legs should be. "Long enough to reach from his body to the ground," he said.
Getting back on topic:
Authors of books like "Clean Code" advertise that every function do only one thing (that's grossly simplified by me here), so in theory your main()
should maybe call an initialization function and then another function orchestrating the work of the application, and that's all.
In practice, many programmers find a lot of tiny functions irritating. A perhaps more useful metric is that a function should usually fit on one screen, if only to make it easier to see and think about.
If a program is complex and most of its functionality is in main()
, someone hasn't done a decent job of breaking the problem down. Essentially you should strive for manageability, understandability and readability. There's usually no good reason for a main() to be huge.
I often find on certain kinds of applications that main() has hundreds of lines of initialization followed by about 20 lines of top-level loop.
It's my habit not to break functions out until I need to call them twice. This sometimes leads to me writing a 300 line function, but as soon as I see the same block occur twice I break that block out.
As for main, initialization routines are often once so 600 lines does not sound unreasonable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With