在“UNIX 环境中的高级编程”第 199 页(第 7.3 节)中,我读到:
If (a) any of these functions [exit, _exit, _Exit] is called without an exit status
我编写了一个简单的程序来验证这一点:
#include <stdio.h>
#include <unistd.h>
int main() {
exit();
}
但是gcc source.c
提示:
source.c:5:5: error: too few arguments to function ‘exit’
这怎么可能?他们的意思是“直接从程序集调用”吗?
编辑:该段落说:
All three exit functions expect a single integer argument, which we call the exit status. Most UNIX System shells provide a way to examine the exit status of a process. If (a) any of these functions is called without an exit status, (b) main does a return without a return value, or (c) the main function is not declared to return an integer, the exit status of the process is undefined.
最佳答案
如果您忘记了原型(prototype)(ANSI C 发明)并简单地将 exit 声明为采用 K&R 风格中未指定数量的参数
void exit();/*unspecified number of parameters*/
那么你可以这样做
void exit();/*unspecified number of parameters*/
int main()
{
exit(1);
}
这是一个格式良好的程序。
使用这种类型的声明,编译器不会阻止您完全省略参数:
void exit();
int main()
{
exit();
}
但这在技术上是未定义的 C。
实际上,exit
位于一个单独的翻译单元(标准库)中,因此编译器无法将其搞乱,并且上述内容是否会崩溃或返回一些垃圾值取决于什么如果代码尝试读取具有未指定内容的寄存器或内存位置,您的机器会执行此操作。
(exit
将尝试抓取的未指定内容可能是“陷阱表示”,然后你会崩溃,否则它只会抓取并使用一些垃圾整数值。)
关于不带参数调用 exit(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57544149/