Question

While reading Programming Pearls, I encountered the program timemod.c available here.

I am not good at C Macros so couldn't figure out what the \ means after each line in the definition of M(op). What is that for? Also what is meant by first line printf(" %-22s", #op);?

Along with this answer if you can point to some good source or tut. for C Prepocessor, it will be appreciated.

Was it helpful?

Solution

couldn't figure out what the \ means after each line in the definition of M(op). What is that for?

Backslash at the (very) end of the line allows the macro definition to continue to the next line. Otherwise it would end at the newline.

Also what is meant by first line printf(" %-22s", #op);?

The # sign is the "stringize operator"; it turns the macro argument op into a string literal by putting double-quotes around it.

Aside from that, %-22s tells printf to print a string with left-justification in 22 characters.

Along with this answer if you can point to some good source or tut. for C Prepocessor, it will be appreciated.

Learning the preprocessor "just happens"… it is a tool of last resort, so expertise in it should not usually be actively sought. I've written a C++11/C99 preprocessor — and it's harder than it sounds — but I have not encountered a good tutorial.

OTHER TIPS

For documentation of the C pre-processor, the GNU compiler documentation is pretty comprehensive, though beware of those parts described as GNU specific extensions if you are not using GCC.

C pre-processor macros must be defined on a single line, but that makes very long macros difficult to read. The \ is an escape character, it removes the next character from the parsing stream, so that in this case it is as if the newline was not there.

The # preceding a proprocessor argumnet turns the argument into a string, so in teh example:

#define PRINT_INT_EXPR( v ) printf( "%s = %d", #v, v ) ;  

Given: int counter = 5 ; PRINT_INT_EXPR( counter ) ;

The output will be: "counter = 5", but equally you could write:

PRINT_INT_EXPR( 1+2+3+4 )

and the output would be: "1+2+3+4+5 = 15".

I would suggest that the example you cite is hardly a "programming pearl" (neither are teh examples of mine above), the definition of the macro M(op) is an example of all that is bad and ill-advised about using function-like macros in C. The fact that you had to ask what it means is evidence enough. The fact that it can be broken by adding a single invisible space or tab character after one of the \ escape characters should leave you recoiling in horror.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top