Should Local Variable Initialisation Be Mandatory?

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

    Always initialize local variables to zero at least. As you saw, there's no real performance it.

    int i = 0;
    struct myStruct m = {0};
    

    You're basically adding 1 or 2 assembly instructions, if that. In fact, many C runtimes will do this for you on a "Release" build and you won't be changing a thing.

    But you should initalize it because you will now have that guarantee.

    One reason not to initialize has to do with debugging. Some runtimes, eg. MS CRT, will initialize memory with predetermined and documented patterns that you can identify. So when you're pouring through memory, you can see that the memory is indeed uninitialized and that hasn't been used and reset. That can be helpful in debugging. But that's during debugging.

提交回复
热议问题