gpt4 book ai didi

c++ - 在 C++ 中调用 main() 本身?

转载 作者:IT老高 更新时间:2023-10-28 23:10:44 26 4
gpt4 key购买 nike

#include <iostream>
#include <cstdlib>

int main() {
cout << "!!!Hello World!!!" << endl;
system("pause");
return main();
}

上述方法有效,但它硬编码了 main() 函数。有没有神奇的变量或宏来获取当前运行的函数?

最佳答案

在“C++”中是否允许?没有。

实际上,你可以调用 main() 吗?是的。

无论 C++ 标准怎么说,这都不会阻止 Linux g++ 编译器使用 main() 中的 main() 编译代码。

#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int y = rand() % 10; // returns 3, then 6, then 7
cout << "y = " << y << endl;
return (y == 7) ? 0 : main();
}

我们可以这样做:

 > g++ g.cpp; ./a.out
y = 3
y = 6
y = 7

查看程序集,我们看到 main 的调用与其他任何函数一样:

main:
...
cmpl $7, -12(%rbp)
je .L7
call main
...
.L7:
...
leave
ret

并不是说这种行为是有保证的,但看起来 g++ 似乎并不真正关心标准,除了这个带有 -pedantic

的讽刺警告
g.cpp:8: error: ISO C++ forbids taking address of function '::main'

关于c++ - 在 C++ 中调用 main() 本身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2532912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com