Have macro 'return' a value

后端 未结 9 1841
闹比i
闹比i 2021-01-31 10:12

I\'m using a macro and I think it works fine -

#define CStrNullLastNL(str) {char* nl=strrchr(str,\'\\n\'); if(nl){*nl=0;}}

So it works to zero out the last

相关标签:
9条回答
  • 2021-01-31 10:45

    If you really want to do this, get a compiler that supports C++0x style lambdas:

    #define CStrNullLastNL(str) [](char *blah) {char* nl=strrchr(blah,'\n'); if(nl){*nl=0;} return blah;}(str)
    

    Although since CStrNullLastNL is basically a function you should probably rewrite it as a function.

    0 讨论(0)
  • 2021-01-31 10:48

    I gave +1 to Mike because he's 100% right, but if you want to implement this as a macro,

    char *CStrNullLastNL_nl; // "private" global variable
    #define nl ::CStrNullLastNL_nl // "locally" redeclare it
    #define CStrNullLastNL( str ) ( \
        ( nl = strrchr( str, '\n') ), /* find newline if any */ \
        nl && ( *nl = 0 ), /* if found, null out */ \
        (char*) nl /* cast to rvalue and "return" */ \
    OR  nl? str : NULL /* return input or NULL or whatever you like */
    )
    #undef nl // done with local usage
    
    0 讨论(0)
  • 2021-01-31 10:55

    to return value from macro:

    bool my_function(int a) {
        if (a > 100)return true;
        return false;
    }
    bool val = my_function(200);
    
    #define my_macro(ret_val,a){\
        if(a > 100 ) ret_val = true;\
        ret_val = false;\
    }
    bool val; my_macro(val, 200);
    
    0 讨论(0)
提交回复
热议问题