c++ - 将未初始化的变量传递给 srand 是个好主意吗?

标签 c++ c srand

将未初始化的变量传递给 srand 而不是 time(NULL) 的结果是个好主意吗?
它是一个 #include 和一个函数调用 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;
}

最佳答案

不,不是。

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

然后,编译您程序的其他人会注意到编译器关于未初始化值的警告并尝试修复它。他可能会正确修复它,或者给出足够复杂的程序,他可能只是将其初始化为零。就是这样'small' bugs turn into huge bugs .


只需将 srand() 替换为 printf() 即可:

#include <stdio.h>

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

    return 0;
}

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

关于c++ - 将未初始化的变量传递给 srand 是个好主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26882023/

相关文章:

c - 预期声明说明符错误,声明外部堆栈时

c++ - srand()的含义

c - rand() 没有给我随机数

c - 用于峰值 EQ 的 IIR 系数,如何将它们传递给 vDSP_deq22?

c++ - 哪个目标文件包含以下静态模板化 "member variable"?

c++ - 方法调用意外地像一个左值

C++模板参数: to find out if a parameter exists in parameter list during compilation time

python - 在 python 中,是否有可能使用预定义变量(例如 C 中的#defined)来控制流程

c - 在函数中使用 srand()

c++ - 赋值期间双重值变化