[Cialug] Learning the 'C' language

Morris Dovey mrdovey at iedu.com
Thu Oct 13 14:01:38 CDT 2005


Brendon J. Colby wrote:

| One thing I saw mentioned was "unit testing." As a (relatively new)
| python programmer, I've begun writing my code with unit testing in
| mind i.e. writing the unit tests before I write the function,
| testing returns for every possible input and output scenario I can
| think of. I think this is a very wise thing to do (testing input
| output scenarios at least, whether before or after writing
| functions). This way any time I change something my unit test will
| (hopefully) tell me if I messed something up.

C's preprocessor makes it easy to incorporate unit test code right into
the application or system using something like:

#define UNIT_TEST
...
#ifdef UNIT_TEST
   /* Unit test code here */
#endif


For individual library functions, I typically include a minimal main
program with "cooked" test data in the same source file, like this:

int function_name(int param)
{  /* function code */
   return value;
}
#ifdef FUNCTION_NAME_TEST
#include <stdio.h>
#include <stdlib.h>
int main(void)
{  int cooked_data[] = /* values for testing */;
   /* Test program code */
   return EXIT_SUCCESS;
}
#endif

This approach ensures that the regression test doesn't "get lost" when
files are backed up, etc.


| Also I'd like emphasize 'Learn how the obfuscated and/or "efficient"
| and/or "mind blowing" code works, don't be tempted to use it in
| production code.' I really despise "cute" code and/or comments. I
| think straight forward, easily readable and self-documenting
| approaches are far more beneficial in the long run. I tend to be
| quite methodical and machine like when I code, even in the
| comments, and stay away from the "mind blowing" and the "cute."
| Although I do like making perl do as much as possible in one line...

In general, yes. Note that legitimate exceptions abound. I worked with a
gentleman on comp.lang.c whose S/390 application was running *way* too
slow. We put together a super-efficient (but messy) piece of code to
replace *one* printf() call. That change caused his program to run in
half the original time - and produced considerable satisfaction for all
involved.

It's worth mentioning, though, that this tuning exercise took place
_after_ the entire application system had been written, debugged, and
made fully functional. Sometimes it's necessary to roll up your sleeves
and make some mud - but it should always be after a best attempt to do a
straightforeward implementation - and it should always be fully
explained in the documentation.

Morris Dovey
C links at http://www.iedu.com/c
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://cialug.org/pipermail/cialug/attachments/20051013/d4a85a07/attachment-0001.html


More information about the Cialug mailing list