我可以声明一个函数而不指定其中一个参数的类型吗?

时间:2011-04-30 17:34:31

标签: c function syntax

可以像这样定义函数:

int foo(int temp1, int temp2 temp3) {
   ...
}

特别是temp2temp3会导致错误吗?如果没有,整体效果如何?

7 个答案:

答案 0 :(得分:5)

你们都错误 ..这完全有效:

#define temp2 blah) { return 1; } int foo_ (int
int foo(int temp1, int temp2 temp3)
{
        return 0;
}

(这是我在早上感觉有点幽默的结果 - 如果你愿意的话可以自由选择;)

答案 1 :(得分:3)

错误是整体效果。

答案 2 :(得分:3)

不,那是无效的C.

答案 3 :(得分:1)

如果你真的试图将三个参数传递给一个函数,但是你只能在编译时知道它们中的两个类型,那么你可以使用一个变量参数列表来完成它。假设您希望第三个参数为intdouble,但您必须首先检查temp1temp2以确定它应该是:

#include <stdarg.h>

int foo(int temp1, int temp2, ...) {
    va_list ap;
    int     temp_int;
    double  temp_double;

    va_start(ap, temp2);
    /*
     * Figure out what type you want the third argument to be
     * and use va_arg(ap, int) or va_arg(ap, double) to pull
     * it off the stack.
     */
    va_end(ap);

    /*
     * Get on with what foo() is really all about (including
     * return an int.
     */
}

这种黑客攻击不会保护你免受某人说foo(1, 2)foo(3, 4, "fish")或类似的诡计,但这是C和C假设你已经长大并对自己的行为负责。

答案 4 :(得分:0)

不,不能。这不起作用,因为temp3实际上不是一个参数。编译器会出现错误。

答案 5 :(得分:0)

如果emp2和temp3是参数,那么每个参数都应该有自己的类型,但这会产生编译错误

答案 6 :(得分:0)

你所写的不是如何调用函数,而是如何声明函数。在每个形式参数之前需要一个数据类型(int temp1,int temp2,int temp3)