c - 在 C 语言中,如何判断函数是否提供了参数?

标签 c ansi-c

在 C 中,当您声明一个不带参数的函数时,该函数可以接受任意数量的参数。示例:

int sum() {
  // some code
}

int subs(void) {
  // some code
}

int main() {
    sum(1, 2, 3, 4, 5, 6); // This is valid
    subs(1, 2, 3, 4, 5, 6); // This is NOT valid
}

在第一种情况(sum)中,如何判断是否提供了某些参数?

提前致谢

最佳答案

How to tell, in C, if parameters to a function are provided?

这是不可能的。从 C 的角度来看,不可能知道是否向此类函数提供了任何参数,也不可能知道它们的计数是多少。

when you declare a function without parameters, that function can accept any number of parameters

是的,当您声明不带参数的函数时。它并不一定意味着该函数接受任意数量的参数。在您提供的代码中:

int sum() {
  // some code
}

这是sum函数定义。在定义中,当函数没有参数时,那么,该函数确实没有参数 - 就像 int sum(void) 一样。来自C11 6.7.6.3p14 ,强调我的:

An identifier list declares only the identifiers of the parameters of the function. An empty list in a function declarator that is part of a definition of that function specifies that the function has no parameters. The empty list in a function declarator that is not part of a definition of that function specifies that no information about the number or types of the parameters is supplied.

您提供的代码无效 - sum 不带任何参数。

所以:

sum(1, 2, 3, 4, 5, 6); // This is also NOT valid

关于c - 在 C 语言中,如何判断函数是否提供了参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65865874/

相关文章:

比较文本文件中的字符串的一行,并在找到时删除该行

c - 显示所有有符号短号码的程序

每行扫描数字的可变数量(scanf)

c - 如何创建比 float ANSI C 更多小数位的变量

c - 如何在C中将节点添加到二叉树?

c - C 中的 SDL 计时器转换为字符串

c - WinPcap:丢弃的 WiFi 数据包

python - 仅使用随机数的有趣任务

java - 以编程方式或通过命令行分析 SSL 证书

C90 - 在全局和函数范围内初始化数组