Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is semicolon ignored in C macro?

Tags:

c

macros

#define A;

#ifdef A
    (...)
#endif

I thought the predecessor would take this as false; however it would goes into this condition. Is A and A; taken as the same?

like image 360
Renjie Avatar asked Sep 05 '15 02:09

Renjie


People also ask

Do macros need a semicolon?

Macro definitions, regardless of whether they expand to a single or multiple statements, should not conclude with a semicolon.

Why #define is not ended with semicolon?

Because preprocessor definitions are substituted before the compiler acts on the source code, any errors that are introduced by #define are difficult to trace. if there is a ; at the end, it's considered as a part of VALUE .

What does a semicolon mean in C?

Role of Semicolon in C: Semicolons are end statements in C. The Semicolon tells that the current statement has been terminated and other statements following are new statements.

Why do Preprocessors dont need a semicolon after the line?

These preprocessor directives extend only across a single line of code. As soon as a newline character is found, the preprocessor directive is considered to end. That's why no semicolon (;) is expected at the end of a preprocessor directive. Save this answer.


1 Answers

No, they're distinct.

In

#define A;

A and ; are two distinct tokens. A is the macro name, and ; is its definition. So you could, if you really wanted to, write:

printf("Hello, world\n")A

and it would be equivalent to

printf("Hello, world\n");

(But please don't do that.)

Since the only thing you do with A is refer to it in an #ifdef, all you're doing is testing whether it's been defined or not, regardless of how it's defined. The semicolon is irrelevant because you don't use it.

Just as a matter of style and clarity, you should always have a space between a macro name and its definition:

#define A ;

This is particularly important if the first token of the expansion is a ( character. If it immediately follows the macro name, you have a function-like macro definition (the macro takes arguments). If there's a space between the macro name and the (, the ( is just part of what the macro expands to.

Speaking of semicolons, a common error is including unnecessary semicolons in macro definitions:

#define THE_ANSWER 42;

...

printf("The answer is %d\n", THE_ANSWER);

Since the semicolon is part of the macro definition, this expands to:

printf("The answer is %d\n", 42;);

which is a syntax error.

like image 147
Keith Thompson Avatar answered Nov 01 '22 10:11

Keith Thompson