Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Negating largest possible negative value in C

Is negating the integer -2^(31) defined as undefined behavior in the C standard or simply -2^(31) again? Trying it the latter holds, but it would be interesting to know how the C standard specifies it.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The standard (n2176 draft) says explictely at 6.5 Expressions § 5:

If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not
mathematically defined or not in the range of representable values for its type), the behavior is
undefined.

We are exactly there: the result is not is the range of representable values for the type, so it is explicitely UB.

That being said, most implementation use 2’complement for negative values and process operations on signed types as the operation on the unsigned type values having the same representation. Which is perfectly defined.

So getting -2^(31) again can be expected on common implementations. But as the standard says that it is UB, it cannot be relied on.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading