Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++;/Java:切换布尔语句?_Java_C++_Boolean_Toggle - Fatal编程技术网

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

C++;/Java:切换布尔语句?,java,c++,boolean,toggle,Java,C++,Boolean,Toggle,有没有切换布尔值的快捷方法 对于整数,我们可以执行如下操作: int i = 4; i *= 4; // equals 16 /* Which is equivalent to */ i = i * 4; 那么,布尔函数是否也有一些东西(比如int的*=操作符) 在C++中: bool booleanWithAVeryLongName = true; booleanWithAVeryLongName = !booleanWithAVeryLongName; // Can it shorter?

有没有切换布尔值的快捷方法

对于整数,我们可以执行如下操作:

int i = 4;
i *= 4; // equals 16
/* Which is equivalent to */
i = i * 4;
那么,布尔函数是否也有一些东西(比如int的
*=
操作符)

在C++中:

bool booleanWithAVeryLongName = true;
booleanWithAVeryLongName = !booleanWithAVeryLongName;
// Can it shorter?
booleanWithAVeryLongName !=; // Or something?
在Java中:

boolean booleanWithAVeryLongName = true;
booleanWithAVeryLongName = !booleanWithAVeryLongName;
// Can it shorter?
booleanWithAVeryLongName !=; // Or something?

没有这样的操作符,但它稍微短了一点:
booleanWithAVeryLongName^=true

不完全是这样,但在C/C++中,有用于按位和/或赋值的运算符

对于表达式之间的逻辑AND/OR,我认为没有


然而,在C语言中,你并没有真正的布尔类型,只有整数,所以你可以使用整数操作符来实现这样的快捷方式。

我认为更好的类比是,你在寻找一元运算符+++
的布尔等价物,我很确定这是不存在的

我从来没有想过,但我想你可以用“真”或“异或”:

booleanWithAVeryLongName ^= TRUE;

不确定它节省了多少钱,但阅读起来有点痛苦。

一个简单的函数(用C++编写)怎么样:

然后你可以像这样使用它:

bool booleanWithAVeryLongName = true;      
toggle(booleanWithAVeryLongName); 

这个主意很有趣,但我不推荐使用它。其他程序员都会浪费5-10秒去理解它的意思。@Max:我同意。但是他问是否有一个更短的方法:)在我看来,其他程序员第一次看到这是一个优点时,会花5-10秒从代码中学习一些东西。在Java/C++中,你能在布尔值上运行位异或吗?您可以在C中使用,但是由于C中的任何非零值都是true,并且true定义为1(至少在Mac OS X上是这样),以上内容在C中被破坏了。无论如何,
booleanWithAVeryLongName=!booleanWithAVeryLongName?现代编辑器有一个很大的特性,叫做代码完成。@杰瑞米:“BooLoAuthAuvyLoNeNo:Lo.true”是C++和java中一个完全有效的构造。当然“^=1”在Java中无效。“booleanWithAVeryLongName=!booleanWithAVeryLongName;”也没有什么问题。包括我在内的大多数人都会这样写。这家伙只是好奇,是否有一个现有的操作符可以做到这一点。
TRUE
定义为1,或者
TRUE
(由Petar回答)。。或者是相同的?我认为返回值可能会导致混淆函数是否改变其参数。我认为一个常见的解决方案是提供两个:
bool toggle\u copy(bool value){return!value;}
bool booleanWithAVeryLongName = true;      
toggle(booleanWithAVeryLongName);