[英]Calling main function more than once is a good practice in C?
I saw a C code like this: 我看到了这样的C代码:
#include <stdio.h>
void main ()
{
static int ivar = 5;
printf ("%d", ivar--);
if (ivar)
main ();
}
which outputs : 哪个输出:
54321
I'm a novice in C and I guess until the condition fails the main
method is called again and again. 我是C的新手,我想直到条件失败,
main
方法被一次又一次地调用。 Since I'm a novice in C, is it good practice to call the main
function more than once as in the above case? 由于我是C的新手,在上述情况下多次调用
main
函数是不错的做法? Are there any real world cases, where this kind of code is very useful? 有没有真实世界的案例,这种代码非常有用?
Thanks in advance. 提前致谢。
In your example, it doesn't matter because it's a very small piece of code. 在您的示例中,它无关紧要,因为它只是一小段代码。 But in the general case I think calling
main
is a bad idea for the following reasons: 但在一般情况下,我认为调用
main
是一个坏主意,原因如下:
main
will be called at one point. main
。 When you see that it is, you have to back track and reread the whole thing. main
is not a meaningful name in the sense that it's not clear what the intent of the recursion is. main
不是一个有意义的名称,因为它不清楚递归的意图是什么。 So I'd write another function with a meaningful name to reflect this. I would say it's rarely, if ever, a good idea to call the main
function. 我会说很少,如果有的话,最好调用
main
函数。 If you're going to recurse, create a function to do it. 如果您要进行递归,请创建一个函数来执行此操作。
A while-loop would be more suitable. while循环更合适。 Recursion makes sense when, with each recursion, you are doing a different job -- typically a smaller one.
当每次递归时,你正在做一个不同的工作 - 通常是一个较小的工作,递归是有道理的。
What this code is really doing is demonstrating function-local static variables: the ivar
is only initialised in the first call of main
. 这段代码真正做的是演示函数本地静态变量:
ivar
仅在main
的第一次调用中初始化。 Each time you recurse, it is decremented despite the ivar=5
statement. 每次递归时,尽管有
ivar=5
语句,但它会递减。
main
has a special meaning. main
有特殊意义。 Idiomatically, it should initialise the environment and then call some other function which drives the application logic. 惯用语,它应该初始化环境 ,然后调用一些驱动应用程序逻辑的其他函数。
An optimising compiler might well transform that code into an iterative version anyway. 无论如何,优化编译器可能会将该代码转换为迭代版本。
This is not often seen (I've never seen it done before), very confusing, since main is supposed to be called once when the program starts and end when the program ends, and largely impractical in most real programs, since you would need to stop the subsequent calls to main() from parsing the command line again. 这种情况不常见(我之前从未见过它),非常令人困惑,因为main应该在程序启动时调用一次,在程序结束时调用,在大多数真实程序中基本上都是不切实际的,因为你需要停止后续调用main()再次解析命令行。
It's far more reasonable to just write a separate recursive function and call it from main and using ordinary function arguments instead of static variables. 只编写一个单独的递归函数并从main调用它并使用普通函数参数而不是静态变量更为合理。
It's called recursion and it can be very useful. 它被称为递归 ,它可能非常有用。 For instance traversing a tree.
例如遍历一棵树。 Some math calculations also use recursion.
一些数学计算也使用递归。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.