简体   繁体   中英

C++ Preprocessor Macros and Return Statement

I want to declare a C++ preprocessor macro for my methods

#define RETURN( expr... )

Where RETURN will return the expression ( return expr; ) if the expression is not empty or just call return ( return; ) without anything if the return type is void.

For instance I tried to do

#define RETURN( expr... ) if ( expr ) { return expr } return;

But if I place this in my program where it expects a non-void return type, it complains that the return-statement has no value because there's a single return; at the end. What is the proper way to do this? Thanks.

#define RETURN(...) return __VA_ARGS__

You don't need to use variadic macros here, because they would just turn into the comma operator anyway . As it turns out, you do want to use a variadic macros! Thanks @chris, I never thought of returning {...} .

Using it looks like:

void foo() {
    RETURN(); //return ;
}
int bar() {
    RETURN(0); //return 0;
}
float RunningOutOfFunctionNames() {
    RETURN(0, 'c', 2.0); //return 0, 'c', 2.0;
                           //AKA return 2.0;
}
std::pair<int, int> ThisOnlyWorksWithVariadicMacros() {
    RETURN({1, 2}); //return {1, 2};
}

I don't see a real use for this outside of some sort of macro factory that produces lots of boilerplate code.

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