Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a macro used in #if be defined?

Tags:

c++

c

macros

# if RTC

/* some code */

# endif

Should the macro RTC be defined with a value? My compiler is not throwing an error. Do all compilers do the same? Isn't defining the macro safer?

like image 425
Surendar Sekar Avatar asked Sep 19 '19 12:09

Surendar Sekar


People also ask

When should we use macro?

A macro is a set of instructions used to execute repetitive tasks. You can record a set of commands and then play them back with one or two keystrokes. That means that you can save A LOT of time when doing routine and repetitive tasks.

Where is macro used?

A macro is an action or a set of actions that you can use to automate tasks. Macros are recorded in the Visual Basic for Applications programming language. You can always run a macro by clicking the Macros command on the Developer tab on the ribbon.

Why is a macro used in?

Macros are used to make a sequence of computing instructions available to the programmer as a single program statement, making the programming task less tedious and less error-prone. (Thus, they are called "macros" because a "big" block of code can be expanded from a "small" sequence of characters.)

Should I use macros in Excel?

Using Excel Macros can speed up work and save you a lot of time. One way of getting the VBA code is to record the macro and take the code it generates. However, that code by macro recorder is often full of code that is not really needed. Also macro recorder has some limitations.


2 Answers

In a preprocessing directive such as this, if the macro is not defined, it is treated as 0.

That is guaranteed by the language.

You can rely on there not being a compilation failure.

Here's the C++ wording:

[cpp.cond]/11: After all replacements due to macro expansion and evaluations of defined-macro-expressions, has-include-expressions, and has-attribute-expressions have been performed, all remaining identifiers and keywords, except for true and false, are replaced with the pp-number 0, and then each preprocessing token is converted into a token. [..]

like image 120
Lightness Races in Orbit Avatar answered Nov 10 '22 11:11

Lightness Races in Orbit


No, it doesn't have to be defined. If the identifier is undefined at the end of an #if expansion, it evaluates to 0.

From ANSI C90:

After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers are replaced with the pp-number 0.

This, however, may not be present in compilers from before C was standardized. I once saw a GCC warning about this (I think it was on MinGW) but I can't find a source for it right now.

Conclusion: All standards-conformant C compilers should not throw an error upon encountering this. You do not need to define the macro before using it in #if.

like image 23
S.S. Anne Avatar answered Nov 10 '22 11:11

S.S. Anne