On May 11, 2017, at 12:26 AM, Kees Dekker <Kees.Dekker@infor.com> wrote:
On Wed, 10 May 2017, Kees Dekker wrote:
2. Adding int value = 0 (or any initializing value what is wanted) does not reduce the readability of the code. If it does, I canʼt imagine how.
Killing warnings this way - kills warnings from all compilers, good and bad. Warnings are meant to expose problems in code, and if they are killed, bugs introduced later might not be detected. In code that will be maintained for thousands of years (I hope) this counts.
It is a good practice to write code like:
int f () { // error return at default int ret = -1; if (all-ok) { // success ret = 0; } return ret; }
It is not necessarily a good practice to write code such as int foo = 0; ... switch (bar) { case ORIGINAL: ... foo = original_foo(...); break; case NEW: ... foo = new_foo(...); break; } If the code is later modified to have a case "NEWER", and that case doesn't do foo = newer_foo(...); then, with a compiler that does good enough data flow analysis to detect foo not being set, then, if foo *weren't* initialized at the beginning of the function, the compiler would catch that; the initialization prevents that. This is, BTW, not a hypothetical example, although, for some reason, my compiler (clang Apple LLVM version 8.1.0 (clang-802.0.42)) didn't seem to catch that; somebody else's compiler (probably some version of GCC) *did* catch that. Their fix was to initialize the variable in its declaration; my fix, after checking the code, was to add code to set it in the case that was missing it, and then adding a default case that set the variable (the variable switched on came from a file, and it *should* have only one of a limited number of values, but nothing other than the code writing the file would prevent it having another value, which the code should *somehow* handle). So it's a tradeoff between "compiler with weaker data flow analysis won't catch the use of an uninitialized variable if you *don't* do a forcible initialization" and "compiler with better data flow analysis won't catch the failure to set the variable if you *do* a forcible initialization". (And I need to figure out how to beat clang into doing the right data flow analysis here - I won't settle for "see, your compiler sux0rs, you need to initialize the variable".)