c - 非可变参数函数如何接受不同数量的参数(与其定义的参数数量不同)?

标签 c function

#include<stdio.h>

int foo();
int bar();

int main(void)
{
  foo(2,3,4);
  return 0;
}

int foo(int a, int b)
{
  return bar(a);
}

int bar(int c, int d)
{
  int e = c + d;
  printf("%d",e);
  return e;
}

输出

5

为什么bar()函数可以接收两个参数?

最佳答案

使用括号作为参数列表的函数声明意味着,函数可以接收的参数的数量和类型没有限制(和检查)。可以使用任意数量和类型的参数来调用它。

FWIW,如果您想指定一个不带参数的函数,则需要指定 void 作为参数列表,例如

 int foo(void);

引用 C11,第 §6.5.2.2 章,函数调用

... If the number of arguments does not equal the number of parameters, the behavior is undefined...

因此,您的程序调用 undefined behaviour 。绝对无法保证或预测您的应用程序将如何运行。

关于c - 非可变参数函数如何接受不同数量的参数(与其定义的参数数量不同)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31238890/

相关文章:

c++ - 在 Netbeans 项目中包含 C++ 库源?

c - 什么时候发生不可读内存页?

C - 强制算术表达式的类型

c++ - 函数指针与函数引用

c - 为 RPC 编码字符串和整数

c - 在c中通过引用传递结构

c - PRQA : How to ignore some specific files?

c - %ms 和 %s scanf 之间的区别

python pandas DataFrame 遍历行并比较两列并应用函数

javascript - 'this' 和普通变量声明的区别