Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

It's not possible. From C perspective there is no possibility to know if any arguments are provided to such function nor what their count is.

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

Yes, when you declare a function without parameters. And it does not necessarily means the function accepts any number of parameters. In the code you presented:

int sum() {
  // some code
}

it's the sum function definition. In a definition, when the function has no parameters, then, well, the function really really has no parameters - it's as if int sum(void). It's from C11 6.7.6.3p14, emphasis mine:

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.

The code you presented is invalid - sum takes no parameters.

So:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...