preprocessor – random notes

I now feel many C/C++ old hands would exploit these preprocessor tricks to the fullest. These tricks are often impossible without using preprocessor.

Some useful tricks —

1) conditional Compilation is nice, but condition Preprocessing offers even more tricks.
1b) you can undefine or redefine a macro including a “macro-function”; you can test if a macro is defined.
These are powerful features only available in the preprocessor. Arguably the #1 popular preprocessor feature.

2) #     error “#e r r o r inside ifdef”  // I used it to debug the preprocessor
    #     error “compiler should never reach here”   // like JUnit fail().

3) __LINE__, __DATE__
4) indent your preprocessor source code with a tab before/after the “#”

——- from [[c++without fear]] ——-
A) #if can comment out code chunks like /* multi-line comment */ but additionally supports nesting!!
A2) #if 1 // to un-comment

B) qq(   defined) comes WITHOUT the pound, is a Boolean function almost exclusively used with #elif (and #if)
C) qq(#define) WITH the pound, is frequently used with just a name, without “content”. Example –

#define MY_CLASS1_INCLUDED // and later
#if defined(MY_CLASS1_INCLUDED)
————
Preprocessor directives can be either 1) macros or 2) conditional compile or 3) includes. Not every directive is a macro.

For debugging, you could even printf from a conditional compile, outside a macro. Compare with #error —
a) no leading “#”. Remember this is conditional compile —

#  ifdef language
//#   error “#e r r o r inside ifdef\n”
      cout<<222<<endl;
      printf(“%d”, language);
#  endif

b) printf can only appear inside a C++ function — basically conditional compilation of the printf statement. In contrast,  #error can appear anywhere in a source file, even before any c++ code.

Advertisements
Posted in IKM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s