Should Local Variable Initialisation Be Mandatory?

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

    This is a great example of Premature optimization is the root of all evil

    The full quote is:

    There is no doubt that the grail of efficiency leads to abuse. Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified.

    This came from Donald Knuth. who are you going to believe...your colleagues or Knuth?
    I know where my money is...

    To get back to the original question: "Should we MANDATE initialization?"
    I would phrase it as so:

    Variables should be initialize, except in situation where it can be demonstrated there is a significant performance gain to be realized by not initializing. Come armed with hard numbers...

提交回复
热议问题