The C preprocessor

The C preprocessor is the first step of the code translation process. It performs some editing tasks before the compiler starts . With Standard C has come a number of useful and powerful techniques that make the preprocessor a genuinely useful tool to the C programmer. The preprocessor is a powerful but must be used carefully (pitfalls)

normally you don’t see the preprocessor output , you can see it by using the -E flag:

One duty of the preprocessor is to remove comments, and replace it with blank lines. If any header files are included, these will also appear in the preprocessor output. This can result in a lot of text.

Some preprocessor identifiers:

For Example you can use it for debug:

Macros and pitfalls:

If we define the following macro:

If we use it with simple parameters it will work fine but if we put some complexity it can cause some pitfalls for example:

Will expand to:

The result is that one of the arguments will increment twice

Names conflicts

We can define a function with the same name as a predefined macro but we need to use parentheses :

The preprocessor will only substitute a macro when the macro is followed by an opening parenthesis (intervening whitespace is allowed). Placing parentheses around the macro name effectively removes the name from the opening parenthesis meaning the preprocessor will leave it alone. It is valid to place parentheses around any C statement without effect

The # operator

The # operator converts macro parameters into strings.

The ## operator

The ## operator provides a portable way of merging separate tokens into one single token.It takes the macro parameters to its right and left and pastes them together. It cannot be the first or last item in a macro.

String Concatenation

Standard C preprocessors concatenate adjacent strings in the input program

#if

#if can be used to test the value of preprocessor constants. A constant integer expression is evaluated. This may not include sizeof, any casts or any enumerated types.

The block should ends with #endif and you can use #elif for complex tests

#ifdef and #if defined

#ifdef can be used to determine if a preprocessor symbol has been defined.

This may be replaced by the defined operator that is more flexible than #ifdef:

Passing Types Into a Macro

Since the preprocessor does not understand C, the following is possible:

 

Tagged

Leave a Reply

Your email address will not be published. Required fields are marked *