简体   繁体   English

为什么我们不能使用C语言实现两个主要功能?

[英]Why can't we have two main functions in C language?

Can someone explain me what happen internally happens, except that main is the start point and we cannot have two start point. 有人可以解释一下内部发生了什么,除了main是起点,我们不能有两个起点。

int main()
{
   int main()
   {
      return 0;
   }
   return 0;
}

This isn't legal C code - in C, functions can't be defined inside of one another. 这不是合法的C代码-在C语言中,不能在一个函数内部定义函数。

There's no fundamental reason that you couldn't do this, but implementing functions like this either complicates the activation record layout and would hurt efficiency (because of considerations like closures) or introduces the potential for memory errors (if you return a pointer to a function inside another function, and the inner function refers to data in the outer function, what happens?) In the interests of simplicity and efficiency, C just doesn't support this. 没有根本的原因不能执行此操作,但是实现这样的功能要么会使激活记录的布局复杂化,并且会(由于诸如闭包之类的考虑)会影响效率,或者会导致潜在的内存错误(如果您返回指向函数的指针)在另一个函数中,而内部函数引用外部函数中的数据,会发生什么?)为了简单和高效,C对此不提供支持。

Hope this helps! 希望这可以帮助!

Standard C doesn't allow defining a function inside another function. 标准C不允许在另一个函数内定义一个函数。 Some compilers support this as an extension, but the names have to be different, otherwise calling a function by its name would be ambiguous. 一些编译器将其作为扩展来支持,但名称必须不同,否则以其名称调用函数将是模棱两可的。

main is the program's entry point. main是程序的入口点。 A program has a single entry point, by definition: it's the function that is executed when the program starts (after some initialization), and the program exits when this function returns (after some cleanup). 根据定义,程序只有一个入口点:它是程序启动时(在一些初始化之后)执行的函数,而当该函数返回时(在一些清除之后)退出程序。

Because the program must have a starting point. 因为程序必须有一个起点。 Function that is named as 'main' is the default starting point in C. That's why 'main' as a name is reserved by the C, and you cannot have another function named 'main'. 名为“ main”的函数是C中的默认起点。这就是C保留“ main”作为名称的原因,并且您不能拥有另一个名为“ main”的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM