4 ms·
That's easy enough to do (and plenty of compilers do it), the problem is determining it for things set conditionally (uncomputable in the the general case) e.g.
by mnarayan01 10y ago
That's easy enough to do (and plenty of compilers do it), the problem is determining it for things set conditionally (uncomputable in the the general case) e.g.:
int y, z;
if (x < 3) { y = 0; }
if (x < 4) { z = y + 1; }
- oldmanhorton 10y agoWell, in the most general case where x's value can only be determined at runtime, most any compiler can and will assume that the initial if could or could not be hit and will therefore assume that y could, conservatively, be uninitialized. Its not uncomputable, its just conservative.
- mnarayan01 10y agoI mean it's undecidable even if x is computed from purely static values: `x` can be the result of an arbitrary C-function and C is Turing complete.
- nitrogen 10y agoIf x is a 32-bit int, then there are only ~4bil possible values to consider. If any of them not ruled out already would lead to an uninitialized read, issue a warning.
- CoolGuySteve 10y agoBut this is still an error when x == 3, y will be uninitialized when z is set. There are plenty of warnings in -Wall that are conservative. For example in g++ C++, out of order constructor initialization even for primitive types is warned for the same reason. In this case the use of y on the RHS without explicit initialization should be warned. It sounds annoying, but having a bug's behaviour change between different build modes is much more irritating.
- mnarayan01 10y agoI probably should have made the second conditional `(x < 2)` rather than `(x < 4)` so that the compiler should not generate a warning. Here a serious compiler would likely be able to statically determine that the variable was always initialized, but for a sufficiently complex function call (even an inlined one) it would not. The compiler could just be "conservative" like you said and warn whenever it couldn't statically determine validity, but note that initializing e.g. `y = 0` has a performance cost (cf. reordering constructor initializers).
- czinck 10y agoI think 90% of developers would rather the compiler just complain there (for any condition in the if). Considering that without the compiler warning/error we have one of the most common sources of hard-to-find bugs, and with the compiler complaining the developer just has to type ` = 0`, it seems like an easy choice to me.