int sampleVariable; // declared and initialized and used elsewhere
if (sampleVariable & 2)
someCodeIwantExecuted();
所以,如果我想手动操作sampleVariable,以便if语句求值为true,而someCodeIwantExecuted()执行,我将执行以下操作?
sampleVariable |= (1 << 1);
请记住,我不知道sampleVariable的值是什么,我想保持其余的位不变。只需更改位,使if语句始终为真。
最佳答案
解决办法相当直接。
// OP suggestion works OK
sampleVariable |= (1 << 1);
// @Adam Liss rightly suggests since OP uses 2 in test, use 2 here.
sampleVariable |= 2
// My recommendation: avoid naked Magic Numbers
#define ExecuteMask (2u)
sampleVariable |= ExecuteMask;
...
if (sampleVariable & ExecuteMask)
注意:使用
(1 << 1)
中的shift样式时,请确保1
的类型与目标类型匹配unsigned long long x;
x |= 1 << 60; // May not work if `sizeof(int)` < `sizeof(x)`.
x |= 1ull << 60;
进一步:考虑
unsigned
类型的优点。// Assume sizeof int/unsigned is 4.
int i;
y |= 1 << 31; // Not well defined
unsigned u;
u |= 1u << 31; // Well defined in C.