Replacing text macros

C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
Function declaration
Lambda function declaration
inline specifier
Exception specifications (deprecated)
noexcept specifier (C++11)
decltype (C++11)
auto (C++11)
alignas (C++11)
Storage duration specifiers
Alternative representations
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Attributes (C++11)
typedef declaration
Type alias declaration (C++11)
Implicit conversions - Explicit conversions
static_cast - dynamic_cast
const_cast - reinterpret_cast
Memory allocation
Class-specific function properties
Special member functions

The preprocessor supports text macro replacement. Function-like text macro replacement is also supported.


[edit] Syntax

#define identifier replacement-list(optional) (1)
#define identifier( parameters ) replacement-list (2)
#define identifier( parameters, ... ) replacement-list (3) (since C++11)
#define identifier( ... ) replacement-list (4) (since C++11)
#undef identifier (5)

[edit] Explanation

[edit] #define directives

The #define directives define the identifier as macro, that is instruct the compiler to replace all successive occurrences of identifier with replacement-list, which can be optionally additionally processed. If the identifier is already defined as any type of macro, the program is ill-formed unless the definitions are identical.

[edit] Object-like macros

Object-like macros replace every occurrence of defined identifier with replacement-list. Version (1) of the #define directive behaves exactly like that.

[edit] Function-like macros

Function-like macros replace each occurrence of defined identifier with replacement-list, additionally taking a number of arguments, which then replace corresponding occurrences of any of the parameters in the replacement-list. The number of arguments must be the same as the number of arguments in macro definition (parameters) or the program is ill-formed. If the identifier is not in functional-notation, i.e. does not have parentheses after itself, it is not replaced at all.

Version (2) of the #define directive defines a simple function-like macro.

Version (3) of the #define directive defines a function-like macro with variable number of arguments. The additional arguments can be accessed using __VA_ARGS__ identifier, which is then replaced with arguments, supplied with the identifier to be replaced.

Version (4) of the #define directive defines a function-like macro with variable number of arguments, but no regular arguments. The arguments can be accessed only with __VA_ARGS__ identifier, which is then replaced with arguments, supplied with identifier to be replaced.

[edit] # and ## operators

In function-like macros, a # operator before an identifier in the replacement-list runs the identifier through parameter replacement and encloses the result in quotes, effectively creating a string literal. In addition, the preprocessor adds backslashes to escape the quotes surrounding embedded string literals, if any, and doubles the backslashes within the string as necessary. All leading and trailing whitespace is removed, and any sequence of whitespace in the middle of the text (but not inside embedded string literals) is collapsed to a single space. This operation is called "stringification". If the result of stringification is not a valid string literal, the behavior is undefined.

When # appears before __VA_ARGS__, the entire expanded __VA_ARGS__ is enclosed in quotes:

#define showlist(...) puts(#__VA_ARGS__)
showlist();            // expands to puts("")
showlist(1, "x", int); // expands to puts("1, \"x\", int")
(since C++11)

A ## operator between any two successive identifiers in the replacement-list runs parameter replacement on the two identifiers (which are not macro-expanded first) and then concatenates the result. This operation is called "concatenation" or "token pasting". Only tokens that form a valid token together may be pasted: identifiers that form a longer identifier, digits that form a number, or operators + and = that form a +=. A comment cannot be created by pasting / and * because comments are removed from text before macro substitution is considered. If the result of concatenation is not a valid token, the behavior is undefined.

Note: some compilers offer an extension that allows ## to appear after a comma and before __VA_ARGS__, in which case the ## does nothing when __VA_ARGS__ is non-empty, but removes the comma when __VA_ARGS__ is empty: this makes it possible to define macros such as fprintf (stderr, format, ##__VA_ARGS__)

[edit] #undef directive

The #undef directive undefines the identifier, that is cancels previous definition of the identifier by #define directive. If the identifier does not have associated macro, the directive is ignored.

[edit] Predefined macros

The following macro names are predefined in any translation unit.

denotes the version of C++ standard that is being used, expands to value 199711L(until C++11), 201103L(C++11), or 201402L(C++14)
(macro constant)
expands to the integer constant 1 if the implementation is hosted (runs under an OS), 0 if freestanding (runs without an OS)
(macro constant)
expands to the name of the current file, as a character string literal, can be changed by the #line directive
(macro constant)
expands to the source file line number, an integer constant, can be changed by the #line directive
(macro constant)
expands to the date of translation, a character string literal of the form "Mmm dd yyyy". The name of the month is as if generated by std::asctime()
(macro constant)
expands to the time of translation, a character string literal of the form "hh:mm:ss"
(macro constant)

The following additional macro names may be predefined by the implementations.

implementation-defined value, if present, typically used to indicate C conformance
(macro constant)
implementation-defined value, if present
(macro constant)
expands to an integer constant of the form yyyymmL, if wchar_t uses Unicode, the date indicates the latest revision of Unicode supported
(macro constant)
expands to 1 if wide character encoding of the basic character set may not equal their narrow encoding
(macro constant)
expands to 1 if the implementation has strict std::pointer_safety
(macro constant)
expands to 1 if the program can have more than one thread of execution
(macro constant)

The values of these macros (except for __FILE__ and __LINE__) remain constant throughout the translation unit. Attempts to redefine or undefine these macros result in undefined behavior.

Note: in the scope of every function body, there is a special function-local predefined variable named __func__(since C++11), defined as a static character array holding the name of the function in implementation-defined format. It is not a preprocessor macro, but it is used together with __FILE__ and __LINE__, e.g. by assert.

[edit] Example

#include <iostream>
//make function factory and use it
#define FUNCTION(name, a) int fun_##name() { return a;}
FUNCTION(abcd, 12)
FUNCTION(fff, 2)
FUNCTION(qqq, 23)
#define FUNCTION 34
#define OUTPUT(a) std::cout << #a << '\n'
int main()
    std::cout << "abcd: " << fun_abcd() << '\n';
    std::cout << "fff: " << fun_fff() << '\n';
    std::cout << "qqq: " << fun_qqq() << '\n';
    std::cout << FUNCTION << '\n';
    OUTPUT(million);               //note the lack of quotes


abcd: 12
fff: 2
qqq: 23

[edit] See also

C documentation for Replacing text macros