Initializing variables in C

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

    There is absolutely no reason why variables shouldn't be initialised, the compiler is clever enough to ignore the first assignment if a variable is being assigned twice. It is easy for code to grow in size where things you took for granted (such as assigning a variable before being used) are no longer true. Consider:

    int MyVariable;
    void Simplistic(int aArg){
        MyVariable=aArg;
    }
    
    //Months later:
    
    int MyVariable;
    void Simplistic(int aArg){
        MyVariable+=aArg; // Unsafe, since MyVariable was never initialized.
    }
    

    One is fine, the other lands you in a heap of trouble. Occasionally you'll have issues where your application will run in debug mode, but release mode will throw an exception, one reason for this is using an uninitialised variable.

提交回复
热议问题