Preprocessor Operators

The # (pound sign) is a preprocessor directive when it occurs as the first non-whitespace character on a line. Also, # and ## perform operator replacement and merging during the preprocessor scanning phase.

Operator #

In C preprocessor, a character sequence enclosed by quotes is considered a token and its content is not analyzed. This means that macro names within quotes are not expanded.

If you need an actual argument (the exact sequence of characters within quotes) as a result of preprocessing, use the # operator in macro body. It can be placed in front of a formal macro argument in definition in order to convert the actual argument to a string after replacement.

For example, let’s have macro LCD_PRINT for printing variable name and value on Lcd:

#define LCD_PRINT(val) Lcd_Out_Cp(#val ": "); \
                       Lcd_Out_Cp(IntToStr(val));

Now, the following code,

LCD_PRINT(temp)

will be preprocessed to this:

 Lcd_Out_Cp("temp" ": "); Lcd_Out_Cp(IntToStr(temp));

Operator ##

Operator ## is used for token pasting. Two tokens can be pasted(merged) together by placing ## in between them (plus optional whitespace on either side). The preprocessor removes whitespace and ##, combining the separate tokens into one new token. This is commonly used for constructing identifiers.

For example, see the definition of macro SPLICE for pasting two tokens into one identifier:

#define SPLICE(x,y) x ## _ ## y

Now, the call SPLICE(cnt, 2) will expand to the identifier cnt_2.

  Note : The mikroC PRO for PIC32 does not support the older nonportable method of token pasting using (l/**/r).
Copyright (c) 2002-2012 mikroElektronika. All rights reserved.
What do you think about this topic ? Send us feedback!
Want more examples and libraries? 
Find them on LibStock - A place for the code