title: Using and returning output in C macro
body: <p>I'm trying to instrument some code to catch and print error messages. Currently I'm using a macro somethng like this:</p>
  
  <pre><code>#define my_function(x) \
    switch(function(x)) { \
      case ERROR: \
        fprintf(stderr, "Error!\n"); \
        break; \
    }
  </code></pre>
  
  <p>Normally, I never capture the function output and this works fine. But I've found a couple cases where I also need the return value of <code>function()</code>. I tried something like the following, but this produces a syntax error.</p>
  
  <pre><code>#define my_function(x) \
    do { \
      int __err = function(x); \
      switch(__err) { \
        case ERROR: \
          fprintf(stderr, "Error!\n"); \
          break; \
      } \
      __err; \
    } while(0)
  </code></pre>
  
  <p>I could declare a global variable to hold the return value of the function, but that looks ugly and my program is multithreaded, so that's likely to cause problems. I'm hoping there's a better solution out there.</p>