具有不同参数的函数

时间:2014-12-28 15:27:54

标签: c function

我想知道如何定义一个接收不同类型参数的函数。

例如,假设我想定义一个" myprint"接收要打印的字符串的函数和显示第一个字符串背景颜色的整数。(我在控制台中更改颜色没有问题。)

但是如果函数只接收第一个字符串,它应该选择背景颜色作为我的默认值,例如黑色。

我认为这个问题可以回答,因为"主要" function具有此功能。它不能接收任何参数,或argc和argv。

我是初学者 C 程序员。

编辑:

Frxstrem的回答之后,我写了这个具有void myPrintf(int backgroundColor,int textColor,char * string)功能的代码,我想要与 Frxstrem' 相同的结果回答两个arg函数:

//suppose I have defined colors
#define first(a,...) (a)
#define second(a,b,...) (b)
#define third(a,b,c,...) (c)
#define myprint(...) (myPrintf(first(__VA_ARGS__,BLACK),second(__VA_ARGS__,GRAY),third(__VA_ARGS__)))
void myPrintf(int backgroundColor,int textColor,char * string){
    int color=16*backgroundColor+textColor;
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),color);
        printf("%s",string);
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),0x07);
}
int main(){
    myprint(,,"hello");//error
}

但是我收到了这个错误:

error C2059: syntax error : ')'

2 个答案:

答案 0 :(得分:4)

由于您的问题实际上是关于提供默认参数,因此您可以利用可变参数宏:

// always returns first and second argument, respectively
#define FIRST(a, ...) (a)
#define SECOND(a, b, ...) (b)

// define the color black as a constant
#define BLACK 0x000000

// our C function
void myprint_(const char *string, int bgcolor);

// our C macro
#define myprint(...) (myprint_(FIRST(__VA_ARGS__), SECOND(__VA_ARGS__, BLACK)))

现在myprint("hello world");扩展到myprint_("hello world", BLACK),而myprint("hello world", 123456)已扩展到myprint_("hello world", 123456)

答案 1 :(得分:1)

虽然Frxstrem的答案是正确的(并且他/她有我的upvote),但过于宽松地使用预处理器宏是一种代码味道。所以纯粹主义者的方法是只声明两个函数,其中一个是对另一个函数的简单调用:

void myprint_color(char* string, int color) {
    ...
}

void myprint(char* string) {
    myprint_color(string, kBackgroundColor);
}

这种方法有两个好处:

  1. 读者非常清楚发生了什么。

  2. 您不必在单个函数体内提供这两个函数的所有功能。 I. e。你可以像这样自由地实现它:

    void myprint(char* string) {
        ...
    }
    
    void myprint_color(char* string, int color) {
        int savedColor = /* get current text color */;
        /* set the text color */
    
        myprint(string);
    
        /* reset the text color to savedColor */
    }
    

    使用这种方法,更简单的功能确实避免了设置颜色,而另一个确实添加了相关代码,而不是总是设置默认为黑色的颜色。

    您可以自由地使用哪种方法更方便实现该功能。您可以稍后决定将实现从一种方法更改为另一种方法,而不会破坏用户端的代码。一旦你有预处理器魔法来提供默认参数的外观,就不能进行这样的改变。