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

if (sampleVariable & 2)
     someCodeIwantExecuted();

したがって、sampleVariable を手動で操作して、if ステートメントが true として評価され、someCodeIwantExecuted() が実行されるようにしたい場合は、次のようにしますか?

sampleVariable |= (1 << 1);

sampleVariable の値がわからないので、残りのビットはそのままにしておく必要があることに注意してください。if ステートメントが常に true になるようにビットを変更するだけです。

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 に答える