Friday 19 February 2010

C Pre-Processor Niceness

I haven't programmed in C for years. 

I have forgotten a little, but I am finding that I am remembering more as I write and test my code.



CPP


The C Pre-Processor is so nice.



This has to be one of the nicest asserts that I have ever used:

ASSERT( 1==0 ); 
which outputs something like this:
ASSERT: "1==0" failed in pc-clisp.c line 672. 
All built with CPP macros:

This turns abc into "abc" - nice. You can use #x in your macro, but the wiki page used QUOTE so I have taken their advice.
#define QUOTE(x) #x
_TEST does the hard work. If the test is false it prints the failed message to stderr with the test, file and line number.
#define _TEST( type , test , action ) {\


  if( !(test) ){ \
    fprintf( stderr ,\
      QUOTE(type) ": %s failed in %s line %d.\n" , "\"" QUOTE(test) "\"" ,\
      __FILE__ ,\
      __LINE__ );\
    action;\
    }\


  }
ASSERT uses the generic _TEST to run the test and if it fails, to exit the program.
#define ASSERT( test ) _TEST( ASSERT , test , exit(1) )
You might like to define TEST and CHECK as well.

TEST just runs the test and prints any failed message.
CHECK, instead, returns false on a failure.
#define CHECK( test ) _TEST( CHECK , test , return (1==0) )
#define TEST( test ) _TEST( TEST , test , )
 For more information, see the wiki entry.

No comments:

Post a Comment

Please use family friendly language.