在C宏中使用和返回输出 [英] Using and returning output in C macro

查看:73
本文介绍了在C宏中使用和返回输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一些代码来捕获和打印错误消息。当前我正在使用这样的宏:

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(function(x)) { \
    case ERROR: \
      fprintf(stderr, "Error!\n"); \
      break; \
  }

通常,我从不捕获函数输出,并且可以正常工作。但是我发现了几种情况,我还需要返回值 function()。我尝试了类似以下的操作,但这会产生语法错误。

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 function(). I tried something like the following, but this produces 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 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.

推荐答案

这是相对复杂的代码,没有太多理由拥有它在宏中。如果您确实希望将其放置在头文件中,则使其为内联(C99)或静态(C89) 。如果使用任何合理的编译器,这都将产生与宏相同的效率。

This is relatively complicated code, there is not much reason to have it in a macro. Make it inline (C99) or static (C89) or both if you really want to place it in a header file. With any reasonable compiler this then should result in the same efficiency as a macro.

这篇关于在C宏中使用和返回输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆