【发布时间】:2011-12-23 00:35:47
【问题描述】:
我似乎无法在 C 标准中找到完全定义具有无符号操作数的一元减号运算符的行为的相关部分。
2003 C++ 标准(是的,C++,请耐心等待几行)在 5.3.1c7 中说:The negative of an unsigned quantity is computed by subtracting its value from 2^n, where n is the number of bits in the promoted operand.
然而,1999 年的 C 标准并没有包含这样一个明确的声明,也没有在 6.5.3.3c1,3 和 6.5c4 中明确定义一元 - 行为。在后者中它说Some operators (the unary operator ~, and the binary operators <<, >>, &, ^, and |, ...) ... return values that depend on the internal representations of integers, and have implementation-defined and undefined aspects for signed types.),它不包括一元减号并且事情似乎仍然模糊。
This earlier question 指的是 K&R ANSI C 书的 A.7.4.5 部分,其中提到了The negative of an unsigned quantity is computed by subtracting the promoted value from the largest value of the promoted type and adding one。
什么是 1999 年的 C 标准,相当于书中的上述引用?
6.2.5c9 说:A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.
是这样吗?还是我还缺少其他东西?
【问题讨论】:
-
<<和>>运算符的结果不依赖于整数的表示。它们被定义为乘法和除以 2 的幂,并且仅对非负操作数进行了明确定义。<<对于负操作数是未定义的,>>对于负操作数是实现定义的。 -
'无符号数量的负数是通过从提升类型的最大值中减去提升值并加一来计算的' - 我知道我的数学功夫与强大的 Ritchie 和Stroustrup,但这似乎是一种糟糕的,也许是疯狂的方式来处理肯定是程序员错误的情况 99.9...% 的时间。为什么不抛出一个编译错误,说“你已经尝试将符号应用于无符号类型,你 dingus”?
-
@CCJ 然后你必须以像
1 + ~a这样的怪异方式来解决这个编译器的智能问题,以关闭编译器,这样就会有人不明白这个表达式的含义。 :)
标签: c unary-operator