Is it good idea to pass uninitialized variable to srand?

前端 未结 5 2098
醉梦人生
醉梦人生 2021-01-20 02:19

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

5条回答
  •  误落风尘
    2021-01-20 02:42

    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 
    
    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 :).

提交回复
热议问题