将未初始化的变量传递给srand是个好主意吗? [英] Is it good idea to pass uninitialized variable to srand?

查看:145
本文介绍了将未初始化的变量传递给srand是个好主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将未初始化的变量传递给 srand 而不是 time(NULL)? >
它是一个 #include 和一个函数调用少。

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.

示例代码:

#include <stdlib.h>

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

而不是

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

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


推荐答案

不, 。

读取未初始化的值会导致未定义的行为。它可以是零,它可以是半随机的 - 但因此,它可以重复是相同的值。它还可能导致编译或运行时错误,或做任何其他完全不可预测的事情。

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.

只需尝试用 srand()替换为 printf c $ c>:

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

#include <stdio.h>

int main()
{
    {
        unsigned seed;
        printf("%u\n", seed);
    }

    return 0;
}



在我的系统上它反复给出 0 。这意味着至少有一个系统,你的代码是破碎的:)。

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

这篇关于将未初始化的变量传递给srand是个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆