这个程序是如何执行的? [英] How does this program execute?

查看:37
本文介绍了这个程序是如何执行的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdlib.h> 
#include <stdio.h> 
int main() 
{ 
    static int i = 5; 
    if(--i){ 
        main(); 
        printf("%d ",i); 
    }
    return 0;
}

上面代码的输出是 0 0 0 0.我首先明白为什么它是 0,但为什么 0 又打印了 3 次?

The output of above code is 0 0 0 0. I get why it is 0 in the first place, but why is 0 printed three more times?

推荐答案

回忆一下 static 变量在对 main 的所有调用之间共享.然后考虑递归执行的代码:

Recall that the static variable is shared between all calls to main. Then consider the code as it is executed recursively:

int main() {
    static int i = 5; // 5
    if (--i) { // 4
        main() {
            if (--i) { // 3
                main() {
                    if (--i) { // 2
                        main() {
                            if (--i) { // 1
                                 main() {
                                     if (--i) // 0 (false)
                                     return 0;
                                 }
                                 printf("%d ",i); // 0
                            }
                            return 0;
                        }
                        printf("%d ",i); // 0
                    }
                    return 0;
                }
                printf("%d ",i); // 0
            }
            return 0;
        }
        printf("%d ",i); // 0
    }
    return 0;
}

这篇关于这个程序是如何执行的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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