Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: unary minus operator behavior with unsigned operands

I can't seem to find the relevant parts in the C standard fully defining the behavior of the unary minus operator with unsigned operands.

The 2003 C++ standard (yes, C++, bear with me for a few lines) says in 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.

The 1999 C standard, however, doesn't include such an explicit statement and does not clearly define the unary - behavior neither in 6.5.3.3c1,3 nor in 6.5c4. In the latter it says 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.), which excludes the unary minus and things seem to remain vague.

This earlier question refers to the K&R ANSI C book, section A.7.4.5 that says The negative of an unsigned quantity is computed by subtracting the promoted value from the largest value of the promoted type and adding one.

What would be the 1999 C standard equivalent to the above quote from the book?

6.2.5c9 says: 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.

Is that it? Or is there something else I'm missing?

like image 919
Alexey Frunze Avatar asked Nov 06 '11 11:11

Alexey Frunze


People also ask

What is a unary minus operator?

The - (unary minus) operator negates the value of the operand. The operand can have any arithmetic type. The result is not an lvalue. For example, if quality has the value 100 , -quality has the value -100 . The result has the same type as the operand after integral promotion.

How do you use unary minus?

In some contexts, - is the unary minus operator. In other contexts, - is the subtraction operator. asks for 12 to be subtracted from 95. means add 3 to negative 12 (resulting in -9).

Is unary operator in C * &?

The unary address-of operator (&) takes the address of its operand. The operand of the address-of operator can be either a function designator or an l-value that designates an object that is not a bit field and is not declared with the register storage-class specifier.


1 Answers

Yes, 6.2.5c9 is exactly the paragraph that you looked for.

like image 160
Roland Illig Avatar answered Sep 21 '22 23:09

Roland Illig