How to call main() from other functions in C

被刻印的时光 ゝ 提交于 2019-12-25 04:40:32

问题


I was going through the difference in C and C++ and I found a tricky point. Can you please elaborate the below points:

  1. In C, we can call main() Function through other Functions.
  2. In C++, we cannot call main() Function through other functions.

How to call main() from another function and what is the use case of it?


回答1:


@TrevorHickey hit the nail on the head (where did his answer go?) - C++ forbids calling main from within a different function (for good reason)... Not that any compiler is likely to stop you (I don't think most of them care).

An obvious workaround would be to move main's functionality into a container function and call it from there, as suggested by @KlasLindbäck.

i.e.

int my_application(int argc, char const * argv[]) {
   // do stuff
   return 0;
}

int main(int argc, char const * argv[]) {
   return my_application()
}

Another "hack" that probably only works because compilers let you call main anyway (As also pointed out by @KlasLindbäck in the comments), would be to use function pointers. i.e.

int main(int argc, char const * argv[]) {
   // do stuff
}

// shouldn't compile... but hey, you never know.
int (*prt_to_main)(int, char const* argv[]) = main;

void test_run(void) {
   prt_to_main(0, NULL);
}


来源:https://stackoverflow.com/questions/38560971/how-to-call-main-from-other-functions-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!