logo

只搜索本站

《21世纪C》翻译网站

第10章 更好的结构

Variadic macros

一个关于Variadic macros的介绍C Note - Variadic Macros

支持变参数的现代风格的函数接口

一个非常好的例子可以参见书中的例子10-12:

#include 
        
typedef struct {                                                   
    double pressure, moles, temp;
} ideal_struct;
        
/** Find the volume (in cubic meters) via the ideal gas law: V =nRT/P
Inputs:
pressure in atmospheres (default 1)
moles of material (default 1)
temperature in Kelvins (default freezing = 273.15)
*/
#define ideal_pressure(...) ideal_pressure_base((ideal_struct){.pressure=1, .moles=1, .temp=273.15, __VA_ARGS__})
double ideal_pressure_base(ideal_struct in){                       
    return 8.314 * in.moles*in.temp/in.pressure;
}

int main(){
    printf("volume given defaults: %g\n", ideal_pressure() );
    printf("volume given boiling temp: %g\n", ideal_pressure(.temp=373.15)); 
    printf("volume given two moles: %g\n", ideal_pressure(.moles=2) );
    printf("volume given two boiling moles: %g\n",
                                ideal_pressure(.moles=2, .temp=373.15));
}
这段代码的关键一句就在第13行,在这一行中,它分别使用了C99新标准中的三个技术: 通过这个三个技术,我们得到了一个具有现代风格的函数接口。