Search code examples
c++csrand

Is it good idea to pass uninitialized variable to srand?


Is it good idea to pass uninitialized variable to srand instead of result of time(NULL)?
It is one #include and one function call less.

Example code:

#include <stdlib.h>

int main(void) {
    {
        usigned seed; //uninitialized
        srand(seed);
    }
    //other code
    return 0;
}

instead of

#include <stdlib.h>
#include <time.h>

int main(void) {
    srand(time(NULL));
    //other code
    return 0;
}

Solution

  • No, it isn't.

    Reading an uninitialized value results in undefined behavior. It can be zero, it can be semi-random — but as such, it can repeatedly be the same value. It may also cause compilation or runtime errors, or do any other completely unpredictable thing.

    Then, someone else compiling your program will notice the compiler warning about uninitialized value and try to fix it. He may fix it correctly, or given complex enough program he may just initialize it to zero. That's how 'small' bugs turn into huge bugs.


    Just try your snippet with srand() replaced by printf():

    #include <stdio.h>
    
    int main()
    {
        {
            unsigned seed;
            printf("%u\n", seed);
        }
    
        return 0;
    }
    

    On my system it repeatedly gives 0. This means that there's at least one system where your code is broken :).