2010-07-23 63 views
1

如何编写调用goto END_标签的宏?在C中的宏预处理中生成标签

对于前:

#define MY_MACRO() \ 
//How to define goto END_##function_name label?? 

my_function() 
{ 
    MY_MACRO(); 

END_my_function: 
    return; 
} 

的MY_MACRO应该简单地用线

goto END_my_function; 
+0

我不认为这是可能的... – kennytm 2010-07-23 12:31:18

回答

3

我不认为这是可以做到替换。尽管一些编译器定义了__FUNCTION____func__,但这些宏并未在宏中扩展。

但是,请注意,您不需要每个功能都有单独的标签:您可以对所有功能使用END,并且只需编写goto END即可。

+0

'__func__'是C99,这是一个字符串,而不是标识符。 – bstpierre 2010-07-23 12:48:07

+0

是啊!我最终这样做了! :) – Bharathwaaj 2010-07-23 12:48:44

1

使用token concatenation

#define MY_MACRO(function_name) END_ ## function_name 
+1

这一点似乎是为了避免显式给出'function_name'。 – lhf 2010-07-23 12:45:53

+0

Doh!我现在看到了,对不起。 – Praetorian 2010-07-23 12:48:29

1

预处理不知道什么功能是在但你可以亲近 - 你必须在函数名传递给这个宏

#include <stdio.h> 

#define GOTO_END(f) goto f ## _end 

void foo(void) 
{ 
    printf("At the beginning.\n"); 

    GOTO_END(foo); 

    printf("You shouldn't see this.\n"); 

    foo_end: 
    printf("At the end.\n"); 
    return; 
} 

int main() 
{ 
    foo(); 
}