布尔运算符 ++ 和 --

2022-01-19 00:00:00 boolean increment c++

今天在编写一些 Visual C++ 代码时,我遇到了一些令我惊讶的事情.似乎 C++ 支持布尔的 ++(增量),但不支持 -- (减量).这只是一个随机决定,还是有某些原因?

Today while writing some Visual C++ code I have come across something which has surprised me. It seems C++ supports ++ (increment) for bool, but not -- (decrement). It this just a random decision, or there is some reason behind this?

这样编译:

static HMODULE hMod = NULL;
static bool once = false;
if (!once++)
    hMod = LoadLibrary("xxx");

这不是:

static HMODULE hMod = NULL;
static bool once = true;
if (once--)
    hMod = LoadLibrary("xxx");

推荐答案

源于使用整数值作为布尔值的历史.

It comes from the history of using integer values as booleans.

如果 xint,但我按照 if(x)... 将其用作布尔值,那么递增将意味着无论它在操作之前的真值如何,它之后都会有一个 true 的真值(除非溢出).

If x is an int, but I am using it as a boolean as per if(x)... then incrementing will mean that whatever its truth value before the operation, it will have a truth-value of true after it (barring overflow).

但是,如果只知道 x 的真值,就无法预测 -- 的结果,因为它可能导致 false(如果整数值为 1)或 true(如果整数值为其他值 - 特别是这包括 0 [false] 和 2 或更多 [true]).

However, it's impossible to predict the result of -- given knowledge only of the truth value of x, as it could result in false (if the integral value is 1) or true (if the integral value is anything else - notably this includes 0 [false] and 2 or more [true]).

所以简写 ++ 有效,而 -- 没有.

So as a short-hand ++ worked, and -- didn't.

++ 允许在 bool 上与此兼容,但在标准中已弃用它,并且在 C++17 中已将其删除.

++ is allowed on bools for compatibility with this, but its use is deprecated in the standard and it was removed in C++17.

这假设我仅使用 x 作为布尔值,这意味着在我经常执行 ++ 之前不会发生溢出足以引起它自己的溢出.即使使用 char 作为使用的类型并且 CHAR_BITS 像 5 一样低,这是 32 次之前这不再起作用(这仍然足以证明这是一种不好的做法,我不是为练习,只是解释它为什么起作用)对于 32 位 int 我们当然必须使用 ++ 2^32 次才能成为问题.使用 -- 虽然它只会导致 false 如果我从 true 的值 1 开始,或者从 0 开始并使用 >++ 之前正好有一次.

This assumes that I only use x as an boolean, meaning that overflow can't happen until I've done ++ often enough to cause an overflow on it's own. Even with char as the type used and CHAR_BITS something low like 5, that's 32 times before this doesn't work any more (that's still argument enough for it being a bad practice, I'm not defending the practice, just explaining why it works) for a 32-bit int we of course would have to use ++ 2^32 times before this is an issue. With -- though it will only result in false if I started with a value of 1 for true, or started with 0 and used ++ precisely once before.

如果我们从一个略低于 0 的值开始,情况就不同了.事实上,在这种情况下,我们可能希望 ++ 导致 false最终值如:

This is different if we start with a value that is just a few below 0. Indeed, in such a case we might want ++ to result in the false value eventually such as in:

int x = -5;
while(++x)
  doSomething(x);

然而,这个例子把 x 视为一个 int 除了条件之外的所有地方,所以它相当于:

However, this example treats x as an int everywhere except the conditional, so it's equivalent to:

int x = -5;
while(++x != 0)
  doSomething(x);

这与仅使用 x 作为布尔值不同.

Which is different to only using x as a boolean.

相关文章