有谁能解释一下这个C程序的执行流程?

时间:2017-03-17 10:11:05

标签: c

此程序运行时没有任何错误。解释以下程序的流程:

int incr(int i) //method definition
{
    static int value=0; //static variable
    value+=i;
    return(value); //returning the value
}

int main(void) {   //main function

    int i; //variable declaration
    for(i=0;i<10;i++)
        i= incr(i);  //method call
    printf("%d\n",i); //printing the value
    return 0;
}

输出为16

2 个答案:

答案 0 :(得分:2)

我想你增加2倍我所以你有0,2,4,8,16 ..... 在循环中添加printf以了解为什么输出此内容。你甚至不试图了解真正发生的事情......

编辑我是愚蠢的你得到 0 1 3 7 15

当你离开循环后,你得到16

int incr(int i) //method definition
{
    /**
    * At first the static will be init at 0 but when you will go back to 
      the function, the static will not be init but keep his value
     */

    static int value = 0; 
    printf("value : %d\n",i); // print 0 0 1 3 7
    value+=i;
    return(value); //returning the value
}

int main(void) {   //main function

int i; //variable declaration
for(i=0;i<10;i++) // you will increment i by i 
{ // Add brackets to see what's really happend 
     i= incr(i);  //i will be static value + i,
     printf("%d\n",i); //printing the value :0 1 3 7 15
}
 printf("%d\n",i); // print 16
 return 0;
}

请记住,c中的静态变量是块内的全局定义。我喜欢在我的c程序中使用静态作为我的主要结构:

struct t_foo *foo my_singleton(struct t_foo *foo)
{

      static t_foo *foo = 0;
      if (foo == 0)
           init_struct(&foo); // basically malloc with some init
      return (foo);
}

在我的主要开头:

 int main()
 {
   struct t_foo *foo;
   foo = my_singleton(foo);
   foo->yolo = 42;
   ...
   return (0);
  } 

在我的程序的任何功能中我都可以:

void any_function(void)
{
      struct t_foo *foo = 0;
      foo = my_singleton(); 
      /**
        Now i can access everithing that was inside my struct
      */
      printf("%d\n", foo->yolo); // print 42
}

当你使用一些图书馆的功能或信号时,它非常有用,而且你无法通过论证中的结构。

答案 1 :(得分:-1)

{}循环后添加for,然后在它们之间编写代码。

例如:

for (int i = 0; i < 100; i++)
{
    //do something
}