C++ Directive With void(0) - c++

What is the purpose of having a directive like below?
#define TEST_CONDITION(con) !(con) ? (void)0:
In particular, I see this called at the start of other directives.
For example,
#define OTHER_CONDITION(..)
TEST_CONDITION(someFunction)
ANOTHER_DIRECTIVE(...)
Doesn't TEST_CONDITION just no-op or a boolean is returned that isn't used in these cases?

Expand the macro, and it becomes clearer. I'll also use some formatting to keep the code readable, and I assume that the lack of some essential escape characters is not meant to be part of the example. OTHER_CONDITION becomes:
!(someFunction)
? (void)0
: ANOTHER_DIRECTIVE(...)
So, the expression someFunction is executed, and if it is true, then ANOTHER_DIRECTIVE(...) (or whatever it expands to) is executed. Otherwise nothing is executed.
Simpler way to write OTHER_CONDITION could be:
#define OTHER_CONDITION(..) if(someFunction) ANOTHER_DIRECTIVE(...)
This simplification lacks some restrictions that TEST_CONDITION provides:
TEST_CONDITION makes it impossible to append an else branch.
TEST_CONDITION makes it ill-formed to use a non-void ANOTHER_DIRECTIVE(...).

Related

C++ Preprocessor Standard Behaviour

I'm studying the C++ standard on the exact behaviour the preprocessor (I need to implement some sort of C++ preprocessor). From what I understand, the example I made up (to aid my understanding) below should be valid:
#define dds(x) f(x,
#define f(a,b) a+b
dds(eoe)
su)
I expect the first function like macro invocation dds(eoe) be replaced by f(eoe, (note the comma within the replacement string) which then considered as f(eoe,su) when the input is rescanned.
But a test with VC++2010 gave me this (I told the VC++ to output the preprocessed file):
eoe+et_leoe+et_l
su)
This is counter-intuitive and is obviously incorrect. Is it a bug with VC++2010 or my misunderstanding of the C++ standard? In particular, is it incorrect to put a comma at the end of the replacement string like I did? My understanding of the C++ standard grammar is that any preprocessing-token's are allowed there.
EDIT:
I don't have GCC or other versions of VC++. Could someone help me to verify with these compilers.
My answer is valid for the C preprocessor, but according to Is a C++ preprocessor identical to a C preprocessor?, the differences are not relevant for this case.
From C, A Reference Manual, 5th edition:
When a functionlike macro call is encoutered, the entire macro call is
replaced, after parameter processing, by a copy of the body. Parameter
processing proceeds as follows. Actual argument token strings are
associated with the corresponding formal parameter names. A copy of
the body is then made in which every occurrence of a formal parameter
name is replace by a copy of the actual parameter token sequence
associated with it. This copy of the body then replaces the macro
call.
[...] Once a macro call has been expanded, the scan for macro calls
resumes at the beginning of the expansion so that names of macros may
be recognized within the expansion for the purpose of further macro
replacement.
Note the words within the expansion. That's what makes your example invalid. Now, combine it with this: UPDATE: read comments below.
[...] The macro is invoked by writing its name, a left parenthesis,
then once actual argument token sequence for each formal parameter,
then a right parenthesis. The actual argument token sequences are
separated by commas.
Basically, it all boils down to whether the preprocessor will rescan for further macro invocations only within the previous expansion, or if it will keep reading tokens that show up even after the expansion.
This may be hard to think about, but I believe that what should happen with your example is that the macro name f is recognized during rescanning, and since subsequent token processing reveals a macro invocation for f(), your example is correct and should output what you expect. GCC and clang give the correct output, and according to this reasoning, this would also be valid (and yield equivalent outputs):
#define dds f
#define f(a,b) a+b
dds(eoe,su)
And indeed, the preprocessing output is the same in both examples. As for the output you get with VC++, I'd say you found a bug.
This is consistent with C99 section 6.10.3.4, as well as C++ standard section 16.3.4, Rescanning and further replacement:
After all parameters in the replacement list have been substituted and # and ##
processing has taken place, all placemarker preprocessing tokens are removed. Then, the
resulting preprocessing token sequence is rescanned, along with all subsequent
preprocessing tokens of the source file, for more macro names to replace.
To the best of my understanding there is nothing in the [cpp.subst/rescan] portions of the standard that makes what you do illegal, and clang and gcc are right in expanding it as eoe+su, and the MSC (Visual C++) behaviour has to be reported as a bug.
I failed to make it work but I managed to find an ugly MSC workaround for you, using variadics - you may find it helpful, or you may not, but in any event it is:
#define f(a,b) (a+b
#define dds(...) f(__VA_ARGS__)
It is expanded as:
(eoe+
su)
Of course, this won't work with gcc and clang.
Well, the problem i see is that the preprocessor does the following
ddx(x) becomes f(x,
However, f(x, is defined as well (even thou it's defined as f(a,b) ), so f(x, expands to x+ garbage.
So ddx(x) finally transforms into x + garbage (because you defined f(smthing, ).
Your dds(eoe) actually expands into a+b where a is eoe and b is et_l .
And it does that twice for whatever reason :).
This scenario you made is compiler specific, depends how the preprocessor chooses to handle the defines expansion.

What's a portable way to implement no-op statement in C++?

One in a while there's a need for a no-op statement in C++. For example when implementing assert() which is disabled in non-debug configuration (also see this question):
#ifdef _DEBUG
#define assert(x) if( !x ) { \
ThrowExcepion(__FILE__, __LINE__);\
} else {\
//noop here \
}
#else
#define assert(x) //noop here
#endif
So far I'm under impression that the right way is to use (void)0; for a no-op:
(void)0;
however I suspect that it might trigger warnings on some compilers - something like C4555: expression has no effect; expected expression with side-effect Visual C++ warning that is not emitted for this particular case but is emitted when there's no cast to void.
Is it universally portable? Is there a better way?
The simplest no-op is just having no code at all:
#define noop
Then user code will have:
if (condition) noop; else do_something();
The alternative that you mention is also a no-op: (void)0;, but if you are going to use that inside a macro, you should leave the ; aside for the caller to add:
#define noop (void)0
if (condition) noop; else do_something();
(If ; was part of the macro, then there would be an extra ; there)
I suspect that it might trigger warnings on some compilers
Unlikely, since ((void)0) is what the standard assert macro expands to when NDEBUG is defined. So any compiler that issues warnings for it will issue warnings whenever code that contains asserts is compiled for release. I expect that would be considered a bug by the users.
I suppose a compiler could avoid that problem by warning for your proposal (void)0 while treating only ((void)0) specially. So you might be better off using ((void)0), but I doubt it.
In general, casting something to void, with or without the extra enclosing parens, idiomatically means "ignore this". For example in C code that casts function parameters to void in order to suppress warnings for unused variables. So on that score too, a compiler that warned would be rather unpopular, since suppressing one warning would just give you another one.
Note that in C++, standard headers are permitted to include each other. Therefore, if you are using any standard header, assert might have been defined by that. So your code is non-portable on that account. If you're talking "universally portable", you normally should treat any macro defined in any standard header as a reserved identifier. You could undefine it, but using a different name for your own assertions would be more sensible. I know it's only an example, but I don't see why you'd ever want to define assert in a "universally portable" way, since all C++ implementations already have it, and it doesn't do what you're defining it to do here.
How about do { } while(0)? Yes it adds code, but I'm sure most compilers today are capable of optimizing it away.
; is considered as standard no-op. Note that it is possible that the compiler will not generate any code from it.
I think the objective here, and the reason not to define the macro to nothing, is to require the user to add a ;. For that purpose, anywhere a statement is legal, (void)0 (or ((void)0), or other variations thereupon) is fine.
I found this question because I needed to do the same thing at global scope, where a plain old statement is illegal. Fortunately, C++11 gives us an alternative: static_assert(true, "NO OP"). This can be used anywhere, and accomplishes my objective of requiring a ; after the macro. (In my case, the macro is a tag for a code generation tool that parses the source file, so when compiling the code as C++, it will always be a NO-OP.)
I'm rather late to the party on this one but I needed the same for a loop() in an Arduino project where all processing is done in timer interrupt service routines (ISR). Found the inline assembler code worked for me without defining a function:
void loop(){
__asm__("nop\n\t"); // Do nothing.
}
I recommend using:
static_cast<void> (0)
And what about:
#define NOP() ({(void)0;})
or just
#define NOP() ({;})
AFAIK, it is universally portable.
#define MYDEFINE()
will do as well.
Another option may be something like this:
void noop(...) {}
#define MYDEFINE() noop()
However, I'd stick to (void)0 or use intrinsics like __noop
inline void noop( ) {}
Self-documenting
this code will not omitted by optimization
static void nop_func() { }
typedef void (*nop_func_t)();
static nop_func_t nop = &nop_func;
for (...)
{
nop();
}
There are many ways, and here is the comparison I've made to some of them in MSVS2019 cpp compiler.
__asm {
nop
}
Transaltes to nop operation in disassembly which takes 1 machine cycle.
do {} while (0); generates some instructions which generates some more cycles.
Simple ; generates nothing.

What's the reason for this no-op while-loop used for assert macro?

I'm reviewing a codebase where assert macro is expanded like this in non-debug configurations:
#define assert( what ) while( 0 )( ( void )1 )
which I don't quite get. Obviously the goal is to have a no-op. Then why not expand into an empty string?
#define assert( what )
What's the reason for this no-op loop?
Most likely to avoid compiler warnings. Check whether this code provokes a warning about an empty statement:
if (foo);
If it does, then do you want the same warning in release mode for the following code?
if (foo) assert(what);
C99 (which is relevant to C++11) also says that assert expands "to a void expression". IIRC, whitespace alone isn't an expression, even though whitespace followed by a semi-colon is an expression-statement. Good old BNF grammar.
By the way, this definition of assert is not standard-conforming. C89 and C99 both say that when NDEBUG is defined, then assert is defined as:
#define assert(ignore) ((void)0)
I'm not sure whether the authors consider it an important requirement, but a program could for example stringify the macro expansion and expect a particular result.
To gobble up the semicolon, most likely. Whether it's needed or not — I don't think it'll make much difference, but at the same time, it doesn't hurt anything, either.

Question about C++ syntax in V8's TYPE_CHECK macro

Once reading v8.h in V8 engine code, I could find the following macro.
#define TYPE_CHECK(T, S) \
while (false) { \
*(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
}
I know that this is to check the type S is compatible with the type T. In the statement, how can the execution flow enter the while loop? while(false) means that condition is always false. Thus, the statement in while loop will never be executed.
As a result, the macro is not always usable, is it?
As a result, the macro is not always usable, is it?
The macro is always usable. The intent is to produce a compile-time error or warning (namely that one type is not compatible with another).
The purpose of wrapping it in while (false) is to prevent the code ever executing at runtime - and with modern compilers the code probably never makes it in to the final binary (optimised out).
If you want to know more about this technique, read up on static assertions.

Rationale on Boost.Preprocessor using macros instead of simple defines?

For example BOOST_PP_ITERATE and BOOST_PP_ITERATION, as seen on GMan's answere here, are preprocessor macros, without any parameters. Is there a reason they're not just simple defines and used as such without ()?
Generally, function like macro can be used to prevent unintentional macro
expansion.
For example, assuming that we have the following macro call:
BOOST_PP_CAT( BOOST_PP_ITERATION, _DEPTH )
and we expect this will be expanded into BOOST_PP_ITERATION_DEPTH.
However, if BOOST_PP_ITERATION is an object like(non-functional) macro,
it will be expanded to its own definition before the token
BOOST_PP_ITERATION_DEPTH is generated by concatenation.
Presumably because they perform operations: consequently, their usage should make it clear that you are actually invoking something and not just using some constant.