C++/Java:切换布尔语句?

Mar*_*aux 6 c++ java boolean toggle

有一个简短的方法来切换布尔值?

使用整数,我们可以执行以下操作:

int i = 4;
i *= 4; // equals 16
/* Which is equivalent to */
i = i * 4;
Run Code Online (Sandbox Code Playgroud)

那么布尔*=运算器也有一些东西(比如整数运算符)?

在C++中:

bool booleanWithAVeryLongName = true;
booleanWithAVeryLongName = !booleanWithAVeryLongName;
// Can it shorter?
booleanWithAVeryLongName !=; // Or something?
Run Code Online (Sandbox Code Playgroud)

在Java中:

boolean booleanWithAVeryLongName = true;
booleanWithAVeryLongName = !booleanWithAVeryLongName;
// Can it shorter?
booleanWithAVeryLongName !=; // Or something?
Run Code Online (Sandbox Code Playgroud)

Pet*_*hev 25

没有这样的运算符,但这有点短: booleanWithAVeryLongName ^= true;

  • IMO,其他程序员花5-10秒钟从他们的代码中学到一些东西,他们第一次看到这是一个好处. (7认同)
  • +1:有趣的伎俩,从未见过这个.:-) (5认同)
  • 有趣的想法,但我不建议使用它.每个其他程序员都会浪费5-10秒来理解它的含义. (4认同)

Nem*_*vic 6

一个简单的函数(在C++中):

void toggle (bool& value) {value = !value;}
Run Code Online (Sandbox Code Playgroud)

然后你使用它像:

bool booleanWithAVeryLongName = true;      
toggle(booleanWithAVeryLongName); 
Run Code Online (Sandbox Code Playgroud)

  • 我认为返回值可能会导致混淆函数是否会改变其参数. (2认同)