For example, what on earth does true+1 means? If it doesn't make sense, why doesn't my G++ raise an error even in -Wall mode?
From the standard:
According to 4.7 (Integral conversions),
4 If the destination type is bool, If the source type is bool, the value false is converted to zero and the value true is converted to one .
In 4.12,
An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.
So true + 1
means 1 + 1
and false + 1
means 0 + 1
.
true+1
is an integer arithmetic operation. true
is converted to 1
and you get 2
.
布尔值在C ++中隐式转换为int
In the declaration
bool x = true + 1;
true
is first promoted to int
; then the addition produces 2; finally the 2 is converted to true
by the rule that any basic type value X
converts to (X != 0)
.
The above also covers update expressions such as x += 1
when x
is of type bool
, because +=
is defined in terms of =
and +
.
However, the use of postfix or prefix ++
on bool
is deprecated. And the use of postfix of prefix --
is invalid. Quoting the 1 Holy Standard, “the operand shall not be of type bool
.”.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.