Initializing variables in C

后端 未结 10 696
长情又很酷
长情又很酷 2020-12-02 12:21

I know that sometimes if you don\'t initialize an int, you will get a random number if you print the integer.

But initializing everything to zero seems

10条回答
  •  执笔经年
    2020-12-02 13:15

    I can think of a couple of reason off the top of my head:

    1. When you're going to be initializing it later on in your code.

      int x;
      
      if(condition)
      {
          func();
          x = 2;
      }
      else
      {
         x = 3;
      }
      anotherFunc(x); // x will have been set a value no matter what
      
    2. When you need some memory to store a value set by a function or another piece of code:

      int x;  // Would be pointless to give x a value here
      scanf("%d", &x);
      

提交回复
热议问题