Initializing variables in C

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

    Initializing a variable, even if it is not strictly required, is ALWAYS a good practice. The few extra characters (like "= 0") typed during development may save hours of debugging time later, particularly when it is forgotten that some variables remained uninitialized.

    In passing, I feel it is good to declare a variable close to its use.

    The following is bad:

    int a;    // line 30
    ...
    a = 0;    // line 40
    

    The following is good:

    int a = 0;  // line 40
    

    Also, if the variable is to be overwritten right after initialization, like

    int a = 0;
    a = foo();
    

    it is better to write it as

    int a = foo();
    

提交回复
热议问题