c++的const用法.我能把它取下来吗?
c++ const use. can i remove it?
我想实现一个快速的随机生成器,我遇到了这个网站:https://en.wikipedia.org/wiki/Xorshift,其中提出了以下代码
#include <stdint.h>
/* The state must be seeded so that it is not everywhere zero. */
uint64_t s[2];
uint64_t xorshift128plus(void) {
uint64_t x = s[0];
uint64_t const y = s[1];
s[0] = y;
x ^= x << 23; // a
s[1] = x ^ y ^ (x >> 17) ^ (y >> 26); // b, c
return s[1] + y;
}
我想知道这里const是否有任何用途,我可以安全地删除它吗?
这里的const
防止y
被意外修改;例如,如果程序员不小心将第四个语句中的x
误输入为y
(y ^= x << 23
),编译器将会报错。
您可以删除它而不会对程序产生语义影响,但我不明白为什么要这样做。
您可以删除const
,但您不应该这样做。
实际上,const
变量声明该变量不能被更改。如果您尝试更改,则无法编译它。如果变量的改变会导致程序的逻辑错误,我们通过使用const
变量来防止它。