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.

Pretty much any existing C compiler will also solve that problem by telling you that it's uninitialized.

  • I tried:

        int test()
        {
            int i;
            return i;
        }
    

    using clang on my Mac mini, and:

        clang -c test.c
    

    and it compiled without complaint.

    • I always build with -Wall so I'm used to seeing the warning:

        > clang -Wall test.c
        test.c:4:16: warning: variable 'i' is uninitialized when used here [-Wuninitialized]
            4 |         return i;
              |                ^
        test.c:3:14: note: initialize the variable 'i' to silence this warning
            3 |         int i;
              |              ^
              |               = 0
        1 warning generated.
      

      For the oldest compiler I have access to, VC++ 6.0 from 1998:

        warning C4700: uninitialized local variable 'i' used

      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 →