在c ++中调用main()本身? [英] Call main() itself in c++?

查看:163
本文介绍了在c ++中调用main()本身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

上面的工作,但它硬编码 main ),是否有一个魔术变量来获取当前运行的函数?

The above works,but it hardcoded the main(),is there a magic variable to get the current running function?

推荐答案

C ++?

在实践中,你可以调用 main()吗?是的。

In practice, can you call main()? Yes.

无论C ++标准如何,这并不会阻止Linux g ++编译器使用 main()编译代码 main()

Whatever the C++ Standard says, that doesn't stop the Linux g++ compiler from compiling code with main() in 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就像任何其他函数一样被调用:

Looking in to the assembly, we see that main is called just like any other function would be:

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

不是保证这种行为,看起来像g ++似乎并不关心标准,除了这个讽刺警告与 -pedantic

Not that this behavior is guaranteed, but it looks like g++ doesn't seem to really care about the standard, apart from this sarcastic warning with -pedantic

g.cpp:8: error: ISO C++ forbids taking address of function '::main'

这篇关于在c ++中调用main()本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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