On 08/10/2012 06:01 PM, Walter Bright wrote:
On 8/10/2012 1:38 AM, F i L wrote:
Walter Bright wrote:
3. Floating point values are default initialized to NaN.

This isn't a good feature, IMO. C# handles this much more conveniently
with just
as much optimization/debugging benefit (arguably more so, because it
catches NaN
issues at compile-time). In C#:

class Foo
{
float x; // defaults to 0.0f

void bar()
{
float y; // doesn't default
y ++; // ERROR: use of unassigned local

float z = 0.0f;
z ++; // OKAY
}
}

This is the same behavior for any local variable,

It catches only a subset of these at compile time. I can craft any
number of ways of getting it to miss diagnosing it. Consider this one:

float z;
if (condition1)
z = 5;
... lotsa code ...
if (condition2)
z++;

To diagnose this correctly, the static analyzer would have to determine
that condition1 produces the same result as condition2, or not. This is
impossible to prove. So the static analyzer either gives up and lets it
pass, or issues an incorrect diagnostic. So our intrepid programmer is
forced to write:

float z = 0;
if (condition1)
z = 5;
... lotsa code ...
if (condition2)
z++;

Now, as it may turn out, for your algorithm the value "0" is an
out-of-range, incorrect value. Not a problem as it is a dead assignment,
right?

But then the maintenance programmer comes along and changes condition1
so it is not always the same as condition2, and now the z++ sees the
invalid "0" value sometimes, and a silent bug is introduced.

This bug will not remain undetected with the default NaN initialization.


To address the concern of static analysis being too hard: I wish we could have it but limit the amount of static analysis that's done. Something like this: the compiler will test branches of if-else statements and switch-case statements, but it will not drop into function calls with ref parameters nor will it accept initialization in looping constructs (foreach, for, while, etc). A compiler is an incorrect implementation if it implements /too much/ static analysis.

The example code you give can be implemented with such limited static analysis:

void lotsaCode() {
        ... lotsa code ...
}

float z;
if ( condition1 )
{
        z = 5;
        lotsaCode();
        z++;
}
else
{
        lotsaCode();
}

I will, in advance, concede that this does not prevent people from just writing "float z = 0;". In my dream-world the compiler recognizes a set of common mistake-inducing patterns like the one you mentioned and then prints helpful error messages suggesting alternative design patterns. That way, bugs are prevented and users become better programmers.

Reply via email to