Should Local Variable Initialisation Be Mandatory?

前端 未结 17 2456
忘掉有多难
忘掉有多难 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:12

    It should be mostly mandatory. The reason for this has nothing to do with performance but rather the danger of using an unitialized variable. However, there are cases where it simply looks ridiculous. For example, I have seen:

    struct stat s;
    s.st_dev = -1;
    s.st_ino = -1;
    s.st_mode = S_IRWXU;
    s.st_nlink = 0;
    s.st_size = 0;
    // etc...
    s.st_st_ctime = -1;
    if(stat(path, &s) != 0) {
       // handle error
       return;
    }
    

    WTF???

    Note that we are handling the error right away, so there is no question about what happens if the stat fails.

提交回复
热议问题