简体   繁体   中英

Passing parameters to a no-op macro in C++

I am getting the following error message

error: '0' cannot be used as a function

when trying to compile the following line:

NOOP(0 != width);

NOOP is defined as follows:

#define NOOP (void)0

The source code is part of a SDK - so it should be okay. And I have found out that (void)0 actually is a valid way to descibe "no operation" in C++. But why would you want to pass a boolean parameter to a function which does nothing? And how do you get rid of the error message?

The MACRO is not defined with any parameters on it, so after the preprocessor replaces code, that statement ends up looking like this:

(void)0(0 != width);

Which confuses the compiler into thinking you are trying to use the "()" operator on 0. (ie using 0 as a function)

I recommend that you drop the "(0 != width)" (it is misleading) and just write NOOP;

" (void)0(0!=width); " is not valid C++, so it's not OK. (void)0; by itself doesn't do anything in C++, so can be used as a noop. Instead of your current define, I would use:

#define NOOP(X) (void)0

This tells the C++ preprocessor that there is a preprocessor function called NOOP that takes one parameter of any type, and replaces that entire function call with (void)0 . So if you have a line of code that says NOOP("HELLO WORLD") , then the preprocessor replaces that entire thing with (void)0 , which the C++ compiler proceeds to ignore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM