在 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/