Using and returning output in C macro

后端 未结 5 1710
说谎
说谎 2021-02-02 12:33

I\'m trying to instrument some code to catch and print error messages. Currently I\'m using a macro somethng like this:

#define my_function(x) \\
  switch(functi         


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-02-02 12:49

    Sorry, this is an edit...

    1. I think you just need the curly braces. No need for the do..while keywords
    2. Make sure that the backslashes are the last characters on each line (no space after).
    3. If you need to get the err value out of the macro, you can just add a parameter

    Like so:

     #define my_function(x, out) \
          { \
            int __err = function(x); \
            switch(__err) { \
              case ERROR: \
                fprintf(stderr, "Error!\n"); \
                break; \
            } \
            __err; \
            (*(out)) = _err; \
          }
    

    To preserve the pass-by-reference C paradigm, you should call my_function this way:

    int output_err;
    
    my_function(num, &output_err);
    

    This way, later, if you decide to make my_function a real function, you don't need to change the call references.

    Btw, qrdl's "Statement Expressions" is also a good way to do it.

提交回复
热议问题