What does the tilde (~) in macros mean? - c++

Seen on this site, the code shows macro invocations using a tilde in parentheses:
HAS_COMMA(_TRIGGER_PARENTHESIS_ __VA_ARGS__ (~))
// ^^^
What does it mean / do? I suspect it to just be an empty argument, but I'm not sure. Is it maybe specific to C(99) like the __VA_ARGS__ is specific to C99 and existent in C++?

On the introduction page of Boost.Preprocessor, an example is given in A.4.1.1 Horizontal Repetition
#define TINY_print(z, n, data) data
#define TINY_size(z, n, unused) \
template <BOOST_PP_ENUM_PARAMS(n, class T)> \
struct tiny_size< \
BOOST_PP_ENUM_PARAMS(n,T) \
BOOST_PP_COMMA_IF(n) \
BOOST_PP_ENUM( \
BOOST_PP_SUB(TINY_MAX_SIZE,n), TINY_print, none) \
> \
: mpl::int_<n> {};
BOOST_PP_REPEAT(TINY_MAX_SIZE, TINY_size, ~) // Oh! a tilde!
#undef TINY_size
#undef TINY_print
An explanation is provided below:
The code generation process is kicked off by calling BOOST_PP_REPEAT, a higher-order macro that repeatedly invokes the macro named by its second argument (TINY_size). The first argument specifies the number of repeated invocations, and the third one can be any data; it is passed on unchanged to the macro being invoked. In this case, TINY_size doesn't use that data, so the choice to pass ~ was arbitrary. [5]
(emphasis mine)
And there is the note:
[5] ~ is not an entirely arbitrary choice. Both # and $ might have been good choices, except that they are technically not part of the basic character set that C++ implementations are required to support. An identifier like ignored might be subject to macro expansion, leading to unexpected results.
The tilde, therefore, is simply a place holder because an argument is required, but none is necessary. Since any user-defined identifier wannabe could be expanded, you need to use something else.
It turns out that ~ is pretty much unused (binary negation is not that often called) in comparison to + or - for example, so there is little chance of confusion. Once you've settled on this, using it consistently gives it a new meaning to the tilde; like using operator<< and operator>> for streaming data has become a C++ idiom.

The ~ does nothing. Almost any other content inside those parentheses would work the same.
The lynchpin of this trick is to test whether _TRIGGER_PARENTHESIS_ is next to (~) in the expansion of _TRIGGER_PARENTHESIS_ __VA_ARGS__ (~). Either way, HAS_COMMA(...) expands its arguments to either 0 or 1.

The arguments to be tested is placed between the macro and its parenthesis, the macro only triggers if the arguments are empty:
_TRIGGER_PARENTHESIS_ __VA_ARGS__ (~)
NOTE: Actually the very link you posted states it. I will check for a reference to this in the standard.

Related

wrapping in do-while-0 vs wrapping in a ternary operator with (void)0

I'm looking at this macro within Microsoft's GSL:
#define GSL_CONTRACT_CHECK(type, cond) \
(GSL_LIKELY(cond) ? static_cast<void>(0) \
: gsl::details::throw_exception(gsl::fail_fast( \
"GSL: " type " failure at " __FILE__ ": " GSL_STRINGIFY(__LINE__))))
Let's simplify it to ignore what I don't care about:
#define CHECK_1(cond) \
(cond ? static_cast<void>(0) : do_something() )
Now, I would intuitively write something like:
#define CHECK_2(cond) \
do { \
if (not (cond)) {do_something();} \
} while(0)
My question: Is there any difference between these wrapping mechanisms? Is there perhaps some corner use case where one causes some unintended compilation gaffe, but not the other?
Note:
This might actually be a C question in disguise, I'm not sure there's any real C++ issue here.
So, my skillz tell me that CHECK_1 and CHECK_2 should be entirely equivalent and only a matter of style. I can't think of why this might not be the case. #NathanOliver seems to agree.
The do while version is a statement while the ternary is an expression. For instance, if assert was defined using a do/while, it couldn't be used in the form
c1 ? x : c2 ? y : (assert(c3), z)
On the other hand, only the do while form allows any multistatements macro definitions in C as a ternary requires expressions as operands.
This distinction makes the choice clear in C: ternary if possible as the macro can be used in more situations ; do while otherwise.
In C++, where macros are still needed in certain situations, at least to short circuit parameter evaluation at compile time when a macro is disabled, the do while form is never the best option (IMHO). I tend to prefer either the ternary form or, even more c++ fashioned: wrapping the macro definition in an anonymous lambda called immediately.
Using a lambda enables multi statements macros just as with do while. It is a single expression as with the ternary. It enables type safety when forwarding the macro arguments to the lambda (you need to trust the compiler to inline that part at runtime, and it will). Passing macro arguments to the lambda prevents name collision between the macro arguments and the macro body. In general it provides scope isolation due to lambda capture being disabled by default. It enables converting varargs to parameter packs for flexibility an type safety starting from c++17. Plus you get a clean stack frame in the debugger when breaking inside the macro.

Can a preprocessor macro expand just some pasted parameters?

I know that in expanding a function-like preprocessor macro, the # and ## tokens in the top-level substitution list essentially act "before" any macro expansions on the argument. For example, given
#define CONCAT_NO_EXPAND(x,y,z) x ## y ## z
#define EXPAND_AND_CONCAT(x,y,z) CONCAT_NO_EXPAND(x,y,z)
#define A X
#define B Y
#define C Z
then CONCAT_NO_EXPAND(A,B,C) is the pp-token ABC, and EXPAND_AND_CONCAT(A,B,C) is the pp-token XYZ.
But what if I want to define a macro that expands just some of its arguments before pasting? For example, I would like a macro that allows only the middle of three arguments to expand, then pastes it together with an exact unexpanded prefix and an exact unexpanded suffix, even if the prefix or suffix is the identifier of an object-like macro. That is, if again we have
#define MAGIC(x,y,z) /* What here? */
#define A X
#define B Y
#define C Z
then MAGIC(A,B,C) is AYC.
A simple attempt like
#define EXPAND(x) x
#define MAGIC(x,y,z) x ## EXPAND(y) ## z
results in an error 'pasting ")" and "C" does not give a valid preprocessing token". This makes sense (and I assume it's also producing the unwanted token AEXPAND).
Is there any way to get that sort of result using just standard, portable preprocessor rules? (No extra code-generating or -modifying tools.)
If not, maybe a way that works on most common implementations? Here Boost.PP would be fair game, even if it involves some compiler-specific tricks or workarounds under the hood.
If it makes any difference, I'm most interested in the preprocessor steps as defined in C++11 and C++17.
Here's a solution:
#define A X
#define B Y
#define C Z
#define PASTE3(q,r,s) q##r##s
#define MAGIC(x,y,z,...) PASTE3(x##__VA_ARGS__,y,__VA_ARGS__##z)
MACRO(A,B,C,)
Note that the invocation "requires" another argument (see below for why); but:
MACRO(A,B,C) here is compliant for C++20
MACRO(A,B,C) will "work" in many C++11/C++17 preprocessors (e.g., gnu/clang), but that is an extension not a C++11/C++17 compliant behavior
I know that in expanding a function-like preprocessor macro, the # and ## tokens in the top-level substitution list essentially act "before" any macro expansions on the argument.
To be more precise, there are four steps to macro expansion:
argument identification
argument substitution
stringification and pasting (in an unspecified order)
rescan and further replacement
Argument identification associates parameters in the macro definition with arguments in an invocation. In this case, x associates with A, y with B, z with C, and ... with a "placemarker" (abstract empty value associated with a parameter whose argument has no tokens). For C++ preprocessors up to C++20, use of a ... requires at least one parameter; since C++20's addition of the __VA_OPT__ feature, use of the ... in an invocation is optional.
Argument substitution is the step where arguments are expanded. Specifically, what happens here is that for each parameter in the macro's replacement list (here, PASTE3(x##__VA_ARGS__,y,__VA_ARGS__##z)), where said parameter does not participate in a paste or stringification, the associated argument is fully expanded as if it appeared outside of an invocation; then, all mentions of that parameter in the replacement list that do not participate in stringification and paste are replaced with the expanded result. For example, at this step for the MAGIC(A,B,C,) invocation, y is the only mentioned qualifying parameter, so B is expanded producing Y; at that point we get PASTE3(x##__VA_ARGS__,Y,__VA_ARGS__##z).
The next step applies pastes and stringification operators in no particular order. Placemarker's are needed here specifically because you want to expand the middle and not the end, and you don't want extra stuff; i.e., to get A to not expand to X, and to stay A (as opposed to changing to "A"), you need to avoid argument substitution specifically. a.s. is avoided in only two ways; pasting or stringifying, so if stringification doesn't work we have to paste. And since you want that token to stay the same as what you had, you need to paste to a placemarker (which means you need one to paste to, which is why there's another parameter).
Once this macro applies the pastes to the "placemarkers", you wind up with PASTE3(A,Y,C); then there is the rescan and further replacement step, during which PASTE3 is identified as a macro invocation. Fast forwarding, since PASTE3 pastes its arguments, a.s. doesn't apply to any of them, we do the pastes in "some order" and we wind up with AYC.
As a final note, in this solution I'm using a varying argument to produce the placemarker token precisely because it allows invocations of the form MACRO(A,B,C) in at least C++20. I'm left-pasting that to z because that makes the addition at least potentially useful for something else (MAGIC(A,B,C,_) would use _ as a "delimiter" to produce A_Y_C).

Why won't my variadic macro accept no arguments correctly?

Overloading Macro on Number of Arguments
https://codecraft.co/2014/11/25/variadic-macros-tricks/
I've been looking at the two links above, trying to get the following code to work:
#define _GET_NUMBER(_0, _1, _2, _3, _4, _5, NAME, ...) NAME
#define OUTPUT_ARGS_COUNT(...) _GET_NUMBER(_0, ##__VA_ARGS__, 5, 4, 3, 2, 1, 0)
...
cout << OUTPUT_ARGS_COUNT("HelloWorld", 1.2) << endl;
cout << OUTPUT_ARGS_COUNT("HelloWorld") << endl;
cout << OUTPUT_ARGS_COUNT() << endl;
This compiles, runs, and gives the following output:
2
1
1
I can not for the life of me figure out why the call OUTPUT_ARGS_COUNT() is giving me 1 instead of 0. I have an ok understanding of the code I'm trying to use, but it's a tad greek to me still so I guess it's possible that I'm not applying something correctly despite the fact I literally copied and pasted the example code from the link on stack overflow.
I'm compiling using g++ 5.4.0 20160609.
Any ideas or additional resources you can point me to would be greatly appreciated.
You can see at http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html:
Second, the ‘##’ token paste operator has a special meaning when placed between a comma and a variable argument. If you write
#define eprintf(format, ...) fprintf (stderr, format, ##__VA_ARGS__)
and the variable argument is left out when the eprintf macro is used, then the comma before the ‘##’ will be deleted. This does not happen if you pass an empty argument, nor does it happen if the token preceding ‘##’ is anything other than a comma.
eprintf ("success!\n")
→ fprintf(stderr, "success!\n");
The above explanation is ambiguous about the case where the only macro parameter is a variable arguments parameter, as it is meaningless to try to distinguish whether no argument at all is an empty argument or a missing argument. CPP retains the comma when conforming to a specific C standard. Otherwise the comma is dropped as an extension to the standard.
So, (unless appropriate extension used) OUTPUT_ARGS_COUNT() is counted as 1 empty argument (comma kept with ##__VA_ARGS__).
The C standard specifies
If the identifier-list in the macro definition does not end with an ellipsis, [...]. Otherwise, there shall be more arguments in the invocation than there are parameters in the macro definition (excluding the ...)
(C2011 6.10.3/4; emphasis added)
C++11 contains language to the same effect in paragraph 16.3/4.
In both cases, then, if your macro invocation were interpreted to have zero arguments then your program would be non-conforming. On the other hand, the preprocessor does recognize and support empty macro arguments -- that is, arguments consisting of zero preprocessing tokens. In principle, then, there is an ambiguity here between no argument and a single empty argument, but in practice, only the latter interpretation results in a conforming program.
That g++ opts for the latter interpretation (the other answer quotes its documentation to that effect) is thus reasonable and appropriate, but it is not safe to rely upon it if you want your code to be portable. A compiler that takes the alternative interpretation would behave differently, possibly by providing the behavior you expected, but also possibly by rejecting the code.

Are empty macro arguments legal in C++11?

I sometimes deliberately omit macro arguments. For example, for a function-like macro like
#define MY_MACRO(A, B, C) ...
I might call it as:
MY_MACRO(, bar, baz)
There are still technically 3 arguments; it's just that the first one is "empty". This question is not about variadic macros.
When I do this I get warnings from g++ when compiling with -ansi (aka -std=c++98), but not when I use -std=c++0x. Does this mean that empty macro args are legal in the new C++ standard?
That's the entirety of my question, but anticipating the "why would you want to?" response, here's an example. I like keeping .h files uncluttered by function bodies, but implementing simple accessors outside of the .h file is tedious. I therefore wrote the following macro:
#define IMPLEMENT_ACCESSORS(TEMPLATE_DECL, RETURN_TYPE, CLASS, FUNCTION, MEMBER) \
TEMPLATE_DECL \
inline RETURN_TYPE* CLASS::Mutable##FUNCTION() { \
return &MEMBER; \
} \
\
TEMPLATE_DECL \
inline const RETURN_TYPE& CLASS::FUNCTION() const { \
return MEMBER; \
}
This is how I would use it for a class template that contains an int called int_:
IMPLEMENT_ACCESSORS(template<typename T>, int, MyTemplate<T>, Int, int_)
For a non-template class, I don't need template<typename T>, so I omit that macro argument:
IMPLEMENT_ACCESORS(, int, MyClass, Int, int_)
If I understand correctly, empty macro argument is allowed since C99 and
C++0x(11).
C99 6.10.3/4 says:
... the number of arguments (including those arguments consisting of
no preprocessing tokens) shall equal the number of parameters ...
and C++ N3290 16.3/4 has the same statement, while C++03 16.3/10 mentions:
... any argument consists of no preprocessing tokens, the behavior is
undefined.
I think empty argument comes under the representation arguments consisting of
no preprocessing tokens above.
Also, 6.10.3 in Rationale for International Standard Programming Languages C rev. 5.10
says:
A new feature of C99: Function-like macro invocations may also now
have empty arguments, that is, an argument may consist of no
preprocessing tokens.
Yes. The relevant bit is 16.3/11
The sequence of preprocessing tokens bounded by the outside-most
matching parentheses forms the list of arguments for the function-like
macro. The individual arguments within the list are separated by comma
preprocessing tokens.
There's no requirement that a single argument corresponds to precisely one token. In fact, the following section makes it clear that there can be more than one token per argument:
Before being substituted, each argument’s preprocessing tokens are
completely macro replaced as if they formed the rest of the
preprocessing file
In your case, one argument happens to correspond to zero tokens. That doesn't cause any contradiction.
[edit]
This was changed by N1566 to bring C++11 in line with C99.
When I do that I normally put a comment in place of the argument.
Place a macro that will be expanded to the empty string.
#define NOARG
...
MY_MACRO(/*Ignore this Param*/ NOARG, bar, baz)
PS. I got no warning with g++ with or without the -std=c++98 flag.
g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3
g++ (Apple Inc. build 5666) 4.2.1

Argument Preceded by a # Token in a Macro

#define LINK_ENTITY_TO_CLASS(mapClassName,DLLClassName) \
static CEntityFactory<DLLClassName> mapClassName( #mapClassName );
This is a macro from the Alien Swarm mod for Half-Life 2, meant to be compiled with MSVC.
I've never seen an argument preceded by a # in a macro before, and I'm not sure if this is a MSVC specific thing or just uncommon. What does it mean?
This is part of both standard C and C++ and is not implementation-specific. The # preprocessing operator stringizes its argument. It takes whatever tokens were passed into the macro for the parameter designated by its operand (in this case, the parameter mapClassName) and makes a string literal out of them. So, for a simple example,
#define STRINGIZE(x) # x
STRINGIZE(Hello World)
// gets replaced with
"Hello World"
Note that the argument tokens are not macro replaced before they are stringized, so if Hello or World were defined as a macro, the result would still be the same. You need to use an extra level of indirection to get the arguments macro replaced (that linked answer discusses the concatenation operator, ##, but applies equally to the stringization operator.