Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do multi-line macros have backslashes at the end of each line?

Tags:

c++

c

In a macro declaration like:

#define WAIT_SPI2_TRANSMISSON_END() {while ((SPI2_SR & SPI_SR_TXCTR_MASK) != 0) {\
                                     if( SPI2_SR & SPI_SR_RFDF_MASK ) {\
                                       (void)SPI2_POPR;\
                                       SPI2_SR |= SPI_SR_RFDF_MASK ;\
                                     }}\

What do these backslashes (\) mean or do there?

like image 361
masmic Avatar asked Nov 04 '13 10:11

masmic


People also ask

How is a multiline macro defined?

We can write multiline macros like functions, but for macros, each line must be terminated with backslash '\' character. If we use curly braces '{}' and the macros is ended with '}', then it may generate some error. So we can enclose the entire thing into parenthesis.

What does ## mean in macro?

The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.

Which symbol is used to define multiline macro in C?

How do you define a multiline macro in C? Use '\' at line endings.

What operator is used to continue the definition of macro in the next line?

Therefore the operator '\' is used for continue the definition of macro in the next line.


2 Answers

It's a line continuation character.

There should be nothing else after it (aside from an end of line character), including white space.

It's particularly useful for macros as it adds clarity.

(Very, very occasionally - especially in old code - you'll see the trigraph sequence ??/ in place of \. These days though it's more of an interviewers' trick question.)

like image 73
Bathsheba Avatar answered Nov 08 '22 08:11

Bathsheba


The slashes are used to make the following end of line a non-linebreak for the preprocessor. A #define has to be exactly one line for the preprocessor. To augment readability you can use the backslashes before the end of lines. The preprocessor will first erase any linebreaks preceded by a backslash and only after that parse the #define. So while you see multiple lines, the PP sees only one.

like image 41
Arne Mertz Avatar answered Nov 08 '22 08:11

Arne Mertz