int nan

Michiel Helvensteijn m.helvensteijn.remove at gmail.com
Sat Jun 27 07:30:29 PDT 2009


BCS wrote:

>> Interesting idea, but IMO using NaN as a default initializer is just a
>> crutch for not having a real system of compile-time
>> detecting/preventing of uninitialized variables from being read (C#'s
>> system for this works very well in my experience).
> 
> I think you can prove that it is impossible to do this totally correctly:
> 
> int i;
> 
> for(int j = foo(); j > 0; j--) i = bar(j);   // what if foo() returns -5?

Complete static analysis of the flow of program control is the holy grail of
compiler construction. It would allow automatic proof of many program
properties (such as initialization). It may not be impossible, but it is
extremely complicated.

If nothing is known about the post-condition of 'foo', the sensible
conclusion would be that 'i' may not be initialized after the loop. If you
know that the return value of 'foo' is always positive under the given
conditions, then you know otherwise.

In the general case, however, you can't guarantee correct static analysis.
This leaves a language/compiler with two options, I believe:

* Do nothing about it. Let the programmer use int.min or set a bool to test
initialization at runtime.

* Add 'uninitialized' to the set of possible states of each type. Every time
a variable is read, assert that it is initialized first. Use the static
analysis techniques that *are* available (a set that will continue to grow)
to eliminate these tests (and the extended state) where possible.

The first method has the advantage of simplicity for the compiler and better
runtime performance in most cases.

The second method has the advantage of automatic detection of subtle bugs
and more simplicity for the programmer.

-- 
Michiel Helvensteijn




More information about the Digitalmars-d mailing list