Using and returning output in macro C

I am trying to process some code to catch and print error messages. I am currently using a macro, for example:

#define my_function(x) \
  switch(function(x)) { \
    case ERROR: \
      fprintf(stderr, "Error!\n"); \
      break; \
  }

Usually I never record the output of a function, and this works fine. But I found a couple of cases where I also need to return the value function(). I tried something like the following, but this leads to a syntax error.

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

I can declare a global variable to hold the return value of the function, but it looks ugly and my program is multi-threaded, which can cause problems. I hope there will be a better solution.

+12
source share
6 answers

, . inline (C99) static (C89) , . , .

+9

GCC

,

#define FOO(A) ({int retval; retval = do_something(A); retval;})

foo = FOO(bar);
+54

. . , , MACROs , . @qrdl, , . -

#define my_function(x, y) ({ \
  int __err = 0; \
  do { \
    __err = function(x, y); \
    switch(__err) { \
      case ERROR: \
        fprintf(stderr, "Error!\n"); \
        break; \
    } \
  } while(0); \
  __err; \
})
+5

, ...

  • , . do..while.
  • , - ( ).
  • err ,

:

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

C-pass-by-reference, my_function :

int output_err;

my_function(num, &output_err);

, my_function , .

Btw, qrdl " " .

+2

( 2 3) 2 \, ?

+1

, -, . :

#define FOO(A) do_something(A)

Here do_something returns some integer. Then you can easily use it, for example:

int a = FOO(a);
-2
source

All Articles