Main Content

Learning to write good programs in C and C++ - separating out repeated code

Archive - Originally posted on "The Horse's Mouth" - 2011-01-04 06:22:41 - Graham Ellis

From our "learning to program in C and C++ day" yesterday - that's how we started our working year in the training business in 2011. "Learning to" courses, where we take people through the basic coding principles and concepts and in the language they'll actually be using are both the hardest work to present, and the most rewarding to the tutor when (s)he sees the results, and I'm delighted we've added these extra days to the front of many of our courses, even though they require me to commit my bank holiday or Sunday to training a small group.

We started off with "Hello World". All programming courses seem to do that - and it's an excellent idea as it's the minimalist program which shows how a program is edited, compiled and run in the source language that's being taught in class. I then expand the "hello world" example to add multiple outputs, outputs from calculations, variables, and inputs too. Yesterday's example went one step further - adding in a conditional too, where King Arthur decided whether to pay in cash or to charge his Excalibur card. [source].

Repeated code should be put into a loop ... and code that's likely to be reused from multiple places in a program should be put into a named block called a function. And that's what I did in the second major example of the day - that's [here]. A further expansion splits the function(s) into a separate file [here], the main code (for this first program) remaining in a different file - [here], and with a separate header file of templates to tell the compiler and loader how the various components of source are related to each other / what parts of the compile will be satisfied later by the loader. Header file example [here].

Courses mentioned in this article - Learning to program in C++ and Learning to program in C. These courses run at our Melksham, Wiltshire training centre and are intended for delegates with little or no prior programming experience. We offer other courses for delegates with prior programming experience who wish to learn C or C++ - see [here].