【发布时间】:2015-04-01 23:06:18
【问题描述】:
如果 C++ 程序将按位非运算符 (~) 应用于布尔值,是否会调用未定义行为?
例如以下程序是否定义明确?
bool f = false;
bool f2 = ~f; // is f2 guaranteed to be true, or is this UB?
bool t = true;
bool t2 = ~t; // is t2 guaranteed to be false, or is this UB?
(是的,我知道有一个更适合这类事情的 ! 运算符;出于这个问题的目的,我们将忽略它的存在;))
【问题讨论】:
-
我猜
~在做任何事情之前将参数提升为int,所以~0 将转换为true。不看就不能百分百确定。 -
@chris,你是对的。
-
是 UB 做
bool b = 13;[或类似的事情]? -
@MatsPetersson:不,
int值13隐式转换为bool,产生true。
标签: c++ bit-manipulation language-lawyer undefined-behavior