language-agnostic - 是否有任何语言具有一元 bool 切换运算符?

标签 language-agnostic bitwise-operators negation

所以这更多的是一个理论问题。 C++ 和直接基于它的语言(Java、C#、PHP)有 shortcut operators用于将大多数二元运算符的结果分配给第一个操作数,例如

a += 3;   // for a = a + 3
a *= 3;   // for a = a * 3;
a <<= 3;  // for a = a << 3;

但是当我想切换 bool 表达式时,我总是发现自己写了类似的东西

a = !a;

a是一个长表达式时,这会很烦人。

this.dataSource.trackedObject.currentValue.booleanFlag =
    !this.dataSource.trackedObject.currentValue.booleanFlag;

(是的,德米特定律,我知道)。

所以我想知道,是否有任何带有一元 bool 切换运算符的语言可以让我缩写 a = !a 而无需重复 的表达式a,例如

!=a;  
// or
a!!;

假设我们的语言有一个正确的 bool 类型(如 C++ 中的 bool),并且 a 属于该类型(因此没有 C 风格的 int a = TRUE)。

如果您能找到记录的来源,我也有兴趣了解例如是否C++ 设计者考虑过在 bool 成为内置类型时添加一个类似的运算符,如果是这样,他们为什么决定反对它。

<小时/>

(注意:我知道有些人认为赋值不应该使用 = 并且 +++= 不是有用的运算符,而是设计缺陷;让我们假设我对它们感到满意并关注为什么它们不会扩展到 bool 值)。

最佳答案

切换 bool 位

... that would allow me to abbreviate a = !a without repeating the expression for a ...

这种方法并不是真正的纯粹的“变异翻转”运算符,但确实满足您的上述标准;表达式的右侧不涉及变量本身。

任何具有 bool 异或赋值的语言(例如 ^= )都允许翻转变量的当前值,例如 a ,通过异或赋值给 true :

// type of a is bool
a ^= true;  // if a was false, it is now true,
            // if a was true, it is now false

正如 @cmaster 在下面的评论中指出的,上面假设 a类型为bool ,而不是例如一个整数或一个指针。如果a实际上是其他东西(例如,非 bool 评估为“真”或“假”值,其位表示分别不是 0b10b0 ),以上内容不成立。

举个具体的例子,Java 是一种定义明确且不受任何静默转换影响的语言。引用下面@Boann 的评论:

In Java, ^ and ^= have explicitly defined behavior for booleans and for integers (15.22.2. Boolean Logical Operators &, ^, and | ), where either both sides of the operator must be booleans, or both sides must be integers. There's no silent conversion between those types. So it's not going to silently malfunction if a is declared as an integer, but rather, give a compile error. So a ^= true; is safe and well-defined in Java.

<小时/>

swift :toggle()

从 Swift 4.2 开始,以下演进提案已被接受并实现:

这会添加 native toggle() 功能到 Bool 输入 Swift。

toggle()

Toggles the Boolean variable’s value.

Declaration

mutating func toggle()

Discussion

Use this method to toggle a Boolean value from true to false or from false to true.

var bools = [true, false]

bools[0].toggle() // bools == [false, false]

这本身不是一个运算符,但确实允许使用语言 native 方法进行 bool 切换。

关于language-agnostic - 是否有任何语言具有一元 bool 切换运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51927109/

相关文章:

c# - 哪些语言支持没有样板代码的返回值缓存?

language-agnostic - 预处理器在现代语言中过时了吗?

javascript - JavaScript 中的否定

编码 : Can anyone explain me this why there are different outputs when comparing Least significant bits of two numbers?

javascript - "&"和 "&&"运算符有什么区别?它们的用途是什么?

c++ - C++ 中的一元否定

python - Python 中带递归的乘法函数

language-agnostic - 计算非对称字节

language-agnostic - 惰性评估和 promise / future 之间的区别

bit-manipulation - 简化按位运算