Comment by WalterBright
4 days ago
From the tutorial:
#include <stdio.h>
int main()
{
int i;
return i;
}
the behaviour is undefined because i’s value is indeterminate.
D solves that problem by initializing variables with the default initializer (in this case 0) if there is not an explicit initializer.
That was in the first version of D because I have spent days tracking down an erratic bug that turned out to be an uninitialized variable.
I think that the right thing to do is to error out though. When the behaviour of some code cannot be guaranteed, that code should just be ruled out imo. Manually initializing a variable generally doesn't clutter the code, arguably it's making it clearer.
Dart does this, you can mark a variable as "late" which tells the compiler that you know for certain the variable will be written too before read. If something reads the variable before it's initialized, then the runtime will error. Maybe even on compile time if it can be caught, I am not certain.
You can do that in GCC now (-ftrivial-auto-var-init=zero). There are a few projects that decided to enable this by default.
Should add it to the C standard.
Pretty much any existing C compiler will also solve that problem by telling you that it's uninitialized.
I tried:
using clang on my Mac mini, and:
and it compiled without complaint.
I always build with -Wall so I'm used to seeing the warning:
For the oldest compiler I have access to, VC++ 6.0 from 1998:
8 replies →
C compilers without arguments start in 'trust me and shut up mode'. Seems to be sensible to me, because the 'I don't care about correctness' typically coincides with writing throwaway code, while you surely have the time to add compiler arguments when you set up the build system for an actual project.
9 replies →
BTW, when D compiles C code, it will default initialize the C variables, too.