Organizing Functions


While meeting with students in beginner level CSCI courses I have noticed a fairly common theme, many students are just typing code into a file with little to no organization. By the end of the project their code is so messy that the flow is almost impossible to follow. Because of this I have put together a simple set of rules for keeping your functions ordered.

The most important thing to understand is how a compiler will read your C code. The file will be read from top down, this means if you define something below where it is referenced the machine will not understand the reference. In addition your include statements will always need to be at the top of the file.

Aside from your main, a function should complete a single process/step. Such as reading data from a file, computing a sum or modifying an array.

If your function becomes to complex then it is best to make a helper function. This function should be defined directly above the function it is assisting. When a function has multiple helpers we will end up with a chronologically ordered set of definitions above the primary function.

It is best to start your main at the bottom of the file and work your way up. the execution will start in main and any call to a function will jump upwards in the file to the desired function. Any return will jump back down to the function call.

This method helps me follow my code with ease however, it is much more important that you keep your practices consistent. If it doesn’t make sense to you then I recommend finding a simpler method. Every problem has a solution and very few problems have a single solution.