INT美孚(INT ARGC,...)与INT富()与在C的int富(无效) [英] int foo (int argc, ...) vs int foo() vs int foo(void) in C

查看:146
本文介绍了INT美孚(INT ARGC,...)与INT富()与在C的int富(无效)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,今天我想(首次承认)的 INT富()其实从 INT富(无效)不同在第一个允许的任何的投入数量,第二个允许的的。

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富()根本不理会任何给定的输入?如果是这样,什么是允许这种形式的功能呢?如果没有,你怎么能访问他们,这是怎么不同于具有可变参数列表(例如像 INT美孚(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 - 其他平台上可能会有所不同)发生的是,呼叫者呼叫被叫方推前所有参数,以相反的顺序,压入堆栈。然后,被叫方可以读出许多这样的参数作为就是了。如果使用富(无效),显然,你无法读取任何。如果使用美孚(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的参数。什么都可以;有没有合同。如果富有采取不同类型作为参数的两种不同的实现这可能是有用的,我希望能够在程序中切换出来。但请记住,编译器不会做(写在汇编程序,在那里你可以处理堆栈和论据自己。函数时,它有时也是有用的)任何类型检查你,所以你必须非常小心。

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()函数,因为它基本上相当于美孚(无效)。富()仅适用于的声明

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.

这篇关于INT美孚(INT ARGC,...)与INT富()与在C的int富(无效)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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