int nan

Michiel Helvensteijn m.helvensteijn.remove at gmail.com
Sun Jun 28 13:06:28 PDT 2009


Nick Sabalausky wrote:

> The fix would be one of the following, depending on what the code is
> actually doing:
> 
> ---------------
> // Instead of knee-jerking i to 0, we default init it to
> // whatever safe value we want it to be if the loop
> // doesn't set it. This, of course, may or may not
> // be zero, depending on the code, but regardless,
> // there are times when this IS perfectly safe.
> 
> int i = contextDependentInitVal;
> for(int j = foo(); j > 3; j--) i = j;
> auto k = i;
> ---------------
> 
> ---------------
> int i;
> bool isSet = false; // making i nullable would be better
> for(int j = foo(); j > 3; j--) {
>     i = j;
>     isSet = true;
> }
> if(isSet) {
>     auto k = i;
> } else { /* handle the problem */ }
> ---------------

Keep in mind that we're talking about a situation in which we're sure 'i'
will always be set. If this is not so, the program is incorrect, and we
would want to see one error or another. Your first solution would be
misleading in that case. Any initial value you choose would be a hack to
silence the compiler. A variation on your second solution then:

int i;
bool isSet = false; // making i nullable would be better
for(int j = foo(); j > 3; j--) {
    i = j;
    isSet = true;
}
assert(isSet);
auto k = i;

This is the basic solution I would always choose in the absence of the
grail. As you say, ideally, the 'uninitialized' state should be part
of 'i', not a separate variable. Reading 'i' would then automatically
assert its initialization at runtime.

I guess that brings us back to one of those scenario's I mentioned in
another subthread. As compilers become more sophisticated, they will be
able to remove the explicit initialization, the test and the extended state
in more complex situations.

> Also, keep in mind that while, under this mechanism, it is certainly
> possible for a coder to cause bugs by always knee-jerking the value to
> zero whenever the compiler complains, that's also a possibility under the
> "holy grail" approach.

That's true. But if we did have the grail, the compiler would also be able
to see that knee-jerking 'i' would not satisfy the contract of the outer
function.

Programmers would learn to say what they mean, not what the compiler wants
to hear.

-- 
Michiel Helvensteijn




More information about the Digitalmars-d mailing list