在宏中使用省略号变量arguements [英] Variable arguements in macro using ellipsis

查看:198
本文介绍了在宏中使用省略号变量arguements的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要定义一个宏接受1或2个参数。双方的参数应该是不同的类型。如何使用省略号,读取参数传递?

下面是示例:

 无效测试(字符* VAR2)
{
 的printf(%S \\ n,VAR2);
}#定义PRINT_STRING(...)(如果(!VAR1)测试(VAR2))INT主(INT ARGC,_TCHAR的argv []){PRINT_STRING(TRUE);
PRINT_STRING(FALSE,你好,世界!);
返回0;
}


解决方案

不要使用宏来做到这一点,使用的可变参数的功能

 无效print_string(布尔should_print,...)
{
    如果(should_print)
    {
        va_list的argp;
        的va_start(argp,should_print);
        字符*字符串=的va_arg(argp,字符*);
        在(string)的printf(%S,字符串);
        va_end用来(argp);    }
}

但是,使用这些事情的时候,因为在va_arg不检查,如果你真的有第二个参数必须非常小心。

此外,使用该接受一个或2个参数的宏,使用GCC绝招(在的此页面):

 的#define PRINT_STRING(应该ARGS ...)print_string(应该,##参数)

(注意逗号之间的空格)

I want to define a macro accepting either 1 or 2 parameters. Both the parameters should be different type. How to use ellipsis and read the arguments passed?

Below is the sample:

void test(char *var2) 
{ 
 printf("%s\n",var2); 
} 

#define PRINT_STRING(...) ( if (!var1) test(var2) ) 

int main(int argc, _TCHAR argv[]) {

PRINT_STRING(TRUE); 
PRINT_STRING(FALSE,"Hello, World!"); 
return 0;
} 

解决方案

Don't use a macro to do that, use a variadic function!

void print_string( bool should_print, ... )
{
    if( should_print )
    {
        va_list argp;
        va_start( argp, should_print);
        char *string = va_arg(argp, char *);
        if( string) printf("%s", string );
        va_end( argp );

    }
}

But be very careful when using these sorts of things, because va_arg doesn't check if you really have a 2nd argument.

Also, to use a macro that accepts one or 2 arguments, use the GCC trick (at the very bottom of this page):

#define PRINT_STRING( should , args... ) print_string( should , ##args )

(note the spaces between the commas)

这篇关于在宏中使用省略号变量arguements的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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