Should Local Variable Initialisation Be Mandatory?

前端 未结 17 2496
忘掉有多难
忘掉有多难 2021-02-14 01:26

The maintenance problems that uninitialised locals cause (particularly pointers) will be obvious to anyone who has done a bit of c/c++ maintenance or enhancement, but I still se

17条回答
  •  南方客
    南方客 (楼主)
    2021-02-14 02:03

    I think it is in most cases a bad idea to initialize variables with an default value, because it simply hides bugs, that are easily found with uninitialized variables. If you forget to get and set the actual value, or delete the get code by accident, you probably never notice it because 0 is in many cases a reasonable value. Mostly it is much easier to trigger those bugs with an value >> 0.

    For example:

    
    void func(int n)
    {
        int i = 0;
    
        ... // Many lines of code
    
        for (;i < n; i++)
            do_something(i);
    

    After some time you are going to add some other stuff.

    
    void func(int n)
    {
        int i = 0;
    
        for (i = 0; i < 3; i++)
            do_something_else(i);
    
        ... // Many lines of code
    
        for (;i < n; i++)
            do_something(i);
    

    Now your second loop won't start with 0, but with 3, depending on what the function does it can be very difficult to find, that there is even a bug.

提交回复
热议问题