【问题标题】:Can I declare a function without specifying a type for one of the parameters?我可以声明一个函数而不为其中一个参数指定类型吗?
【发布时间】:2011-04-30 17:34:30
【问题描述】:

函数可以这样定义吗:

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

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

【问题讨论】:

  • 您的意思是 "defined," 不是 "called" - 为什么不自己尝试一下,看看它是否会产生编译器错误?跨度>
  • 您从哪里得知这可能是有效的?
  • 给社区的一个问题:对这种问题回答“LOL”太苛刻了?
  • @akappa:不在评论中,没有。
  • 这个声明是什么意思,即什么值可以作为这个函数的第三个参数传递,它们将如何处理?

标签: c function syntax


【解决方案1】:

你们都错了..这完全适用于:

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

(这是我早上第一件事感到有点幽默的结果 - 如果您愿意,请随意投反对票;))

【讨论】:

  • 在这种情况下,整体效果会让未来的维护者发疯
  • @blueraja - 绝对是我想要的:)
  • @oli: 决定我确实喜欢没有* :) +1
  • #define temp2 blah) { return 1; } int foo_ (int 怎么样?
【解决方案2】:

错误是整体效果。

【讨论】:

  • 标记为 CW,因为我不应该因为这样的答案而获得声誉。
【解决方案3】:

不,那不是有效的 C。

【讨论】:

    【解决方案4】:

    如果您真的想将三个参数传递给一个函数,但您在编译时只知道其中两个的类型,那么您可以使用变量参数列表来完成。假设您希望第三个参数是 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.
         */
    }
    

    这种 hack 不会保护您免受有人说 foo(1, 2)foo(3, 4, "fish") 或类似恶作剧的伤害,但这是 C 和 C 假设您已经长大并为自己的行为负责。

    【讨论】:

      【解决方案5】:

      不,它不能。这不起作用,因为 temp3 并不是真正的参数。编译器会报错。

      【讨论】:

        【解决方案6】:

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

        【讨论】:

          【解决方案7】:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-05-06
            • 1970-01-01
            • 2017-11-13
            • 1970-01-01
            • 2023-01-30
            • 2011-03-20
            相关资源
            最近更新 更多