Should Local Variable Initialisation Be Mandatory?

前端 未结 17 2443
忘掉有多难
忘掉有多难 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条回答
  •  梦毁少年i
    2021-02-14 02:04

    As you've showed with respect to performacne it does not make a difference. The compiler will (in optimized builds) detect if a local variable is written without beeing read from and remove the code unless it has other side-effects.

    That said: If you initialize stuff with simple statements just to be sure it's initialized it's fine to do so.. I personally don't do it, for a single reason:

    It tricks the guys who may later maintain your code into thinking that the initialization is required. That little foo = 0; will increase the code-complexity. Other than that it's just a matter of taste.

    If you unnessesary initialize variables via complex statements it may have a side-effect.

    For example:

      float x = sqrt(0);
    

    May be optimized by your compiler if you are lucky and work with a clever compiler. With a not so clever compiler it may as well result in a costly and unnessesary function-call because sqrt can - as a side-effect - set the errno variable.

    If you call functions that you have defined yourself my best bet is, that the compiler always assumes that they may have side-effects and don't optimize them out. That may be different if the function happen to be in the same translation unit or you have whole program optimization turned on.

提交回复
热议问题