1
int sampleVariable; // declared and initialized and used elsewhere

if (sampleVariable & 2)
     someCodeIwantExecuted();

因此,如果我想手动操作 sampleVariable 以便 if 语句评估为 true 并执行 someCodeIwantExecuted() 我会执行以下操作?

sampleVariable |= (1 << 1);

请记住,我不知道 sampleVariable 的值是什么,我想保持其余位相同。只需更改该位,以便 if 语句始终为真。

4

1 回答 1

0

解决方案相当直接。

//  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)

注意:在使用 shift 样式时(1 << 1),请确保类型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.
于 2013-10-23T00:42:24.480 回答