Initializing variables in C

后端 未结 10 697
长情又很酷
长情又很酷 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:12

    It's always good practice to initialize your variables, but sometimes it's not strictly necessary. Consider the following:

    int a;
    for (a = 0; a < 10; a++) { } // a is initialized later
    

    or

    void myfunc(int& num) {
      num = 10;
    }
    
    int a;
    myfunc(&a); // myfunc sets, but does not read, the value in a
    

    or

    char a;
    cin >> a; // perhaps the most common example in code of where
              // initialization isn't strictly necessary
    

    These are just a couple of examples where it isn't strictly necessary to initialize a variable, since it's set later (but not accessed between declaration and initialization).

    In general though, it doesn't hurt to always initialize your variables at declaration (and indeed, this is probably best practice).

提交回复
热议问题