C 中的 int foo (int argc, ...) vs int foo() vs int foo(void) [英] int foo (int argc, ...) vs int foo() vs int foo(void) in C

查看:28
本文介绍了C 中的 int foo (int argc, ...) vs int foo() vs int foo(void)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以今天我认为(这是第一次承认)int foo() 实际上与 int foo(void) 不同,因为第一个允许 任意个输入,第二个允许.

So today I figured (for the first time admittedly) that int foo() is in fact different from int foo(void) in that the first one allows any number of inputs and the second one allows zero.

int foo() 是否会忽略任何给定的输入?如果是这样,那么允许这种形式的功能有什么意义呢?如果没有,您如何访问它们以及这与拥有可变参数列表(例如 int foo (int argc, ...) 之类的东西)有何不同?

Does int foo() simply ignore any given inputs? If so, what's the point of allowing this form of function? If not, how can you access them and how is this different from having a variable argument list (e.g. something like int foo (int argc, ...))?

推荐答案

理解这一点的关键是理解调用堆栈.当您在 C 中调用函数(使用标准 x86 ABI — 其他平台可能会有所不同)时,调用者会在调用被调用者之前以相反的顺序将所有参数压入堆栈.然后,被调用者可以根据需要读取尽可能多的这些参数.如果您使用 foo(void),显然您不会读取任何内容.如果您使用 foo(int),您将能够将一个单词读入当前帧下方的堆栈中.

The key to understanding this is understanding the call stack. What happens when you call a function in C (with the standard x86 ABI — other platforms may vary) is that the caller pushes all of the arguments, in reverse order, onto the stack before calling the callee. Then, the callee can read as many of those arguments as it wants. If you use foo(void), obviously you won't read any. If you use foo(int), you'll be able to read one word into the stack below your current frame.

使用 foo()(没有指定参数)意味着编译器不会关心你传递给 foo 的参数.什么都可以;没有合同.如果 foo 有两种不同的实现,它们采用不同的类型作为参数,这可能很有用,并且我希望能够以编程方式将它们切换出来.(在汇编程序中编写函数有时也很有用,您可以自己处理堆栈和参数.)但请记住,编译器不会为您进行任何类型检查,因此您必须非常小心.

Using foo() (with no args specified) means that the compiler won't care to check the arguments you pass to foo. Anything goes; there's no contract. This can be useful if foo has two different implementations that take different types as arguments, and I want to be able to switch them out programmatically. (It's also sometimes useful when writing functions in assembler, where you can handle the stack and arguments yourself.) But remember that the compiler is not going to do any type-checking for you, so you have to be very careful.

这与 foo(int, ...) 不同,因为在这种情况下,该函数实际上有一种方法可以访问所有参数(使用可变参数).没有理由用 foo() 实际定义一个函数,因为它基本上等同于 foo(void).foo() 仅对声明有用.

This is different from foo(int, ...), since in that case, the function actually has a way to access all of the arguments (using varargs). There's no reason ever to actually define a function with foo(), since it's basically equivalent to foo(void). foo() is only useful for declarations.

这篇关于C 中的 int foo (int argc, ...) vs int foo() vs int foo(void)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆