(x || !x) 什么时候为假?
When is (x || !x) false?
我的一个朋友开玩笑地问我这个问题。这本来是一个 "goes without saying" 类型的评论,但后来我实际上考虑了一段时间并开始想出一些聪明的“almost 解决方案”。
第一次尝试:
If C ever supports quantum computing there may be an answer to this. A q-bit can be in many states at once, so it could be false AND true and this conditional will return (BOOL)0.5
aka "Yes/no/maybe-so" - but once you observe the variable the whole thing will collapse and become invalid again.
第二次尝试:
If X could somehow be defined as a random binary generator and you cast it to a BOOL you could get false some of the time. I'm not sure if you can do this though in C unless you use CLANG. #define x (BOOL)!!(rand()%2)
我们讨论的语言是 C,但我也很好奇是否有人可以用 any 语言找到任何解决方案。
当x
是volatile(volatile int x
),被外部线程/设备修改时,表达式可以是false.
宏在这里确实是作弊,但您不需要与布尔类型或特殊编译器有任何关系。以下据我所知是合法的标准C.
#include <stdio.h>
int f(void) {
static int y = 0;
if (y == 0) {
y = 1;
return 0;
} else {
return 1;
}
}
#define x f()
int main(void) {
if (x || !x) {
puts("It was true");
} else {
puts("It was false");
}
return 0;
}
或者更简洁:
int y = 0;
#define x y++
(对于那些担心未定义行为的人,请注意 ||
左右两侧之间有一个序列点。)
这有点小技巧,但以下解决方案也有效:
#define x 1 ? 0 : 1
(x || !x)
原因在于运算符的优先级。预处理后 (x || !x)
解析为以下内容(添加括号以显示优先级):
(1 ? 0 : (1 || !1) ? 0 : 1)
一个更简单的宏:
#define x 0&0
扩展 (x || !x)
得到 (0 & 0 || !0 & 0)
,它总是错误的。
同样:
#define x 0*0
#define x 1*0 // for binary buffs
#define x 4&2 // for HHGG fans.
我找不到 2 个字母的宏:(
在 JS 中尝试过:
var i = 0
i++ || !(i++)
注意:此解决方案仅在 i = 0
时有效
我的一个朋友开玩笑地问我这个问题。这本来是一个 "goes without saying" 类型的评论,但后来我实际上考虑了一段时间并开始想出一些聪明的“almost 解决方案”。
第一次尝试:
If C ever supports quantum computing there may be an answer to this. A q-bit can be in many states at once, so it could be false AND true and this conditional will return
(BOOL)0.5
aka "Yes/no/maybe-so" - but once you observe the variable the whole thing will collapse and become invalid again.
第二次尝试:
If X could somehow be defined as a random binary generator and you cast it to a BOOL you could get false some of the time. I'm not sure if you can do this though in C unless you use CLANG.
#define x (BOOL)!!(rand()%2)
我们讨论的语言是 C,但我也很好奇是否有人可以用 any 语言找到任何解决方案。
当x
是volatile(volatile int x
),被外部线程/设备修改时,表达式可以是false.
宏在这里确实是作弊,但您不需要与布尔类型或特殊编译器有任何关系。以下据我所知是合法的标准C.
#include <stdio.h>
int f(void) {
static int y = 0;
if (y == 0) {
y = 1;
return 0;
} else {
return 1;
}
}
#define x f()
int main(void) {
if (x || !x) {
puts("It was true");
} else {
puts("It was false");
}
return 0;
}
或者更简洁:
int y = 0;
#define x y++
(对于那些担心未定义行为的人,请注意 ||
左右两侧之间有一个序列点。)
这有点小技巧,但以下解决方案也有效:
#define x 1 ? 0 : 1
(x || !x)
原因在于运算符的优先级。预处理后 (x || !x)
解析为以下内容(添加括号以显示优先级):
(1 ? 0 : (1 || !1) ? 0 : 1)
一个更简单的宏:
#define x 0&0
扩展 (x || !x)
得到 (0 & 0 || !0 & 0)
,它总是错误的。
同样:
#define x 0*0
#define x 1*0 // for binary buffs
#define x 4&2 // for HHGG fans.
我找不到 2 个字母的宏:(
在 JS 中尝试过:
var i = 0
i++ || !(i++)
注意:此解决方案仅在 i = 0