Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsigned negative primitives?

In C++ we can make primitives unsigned. But they are always positive. Is there also a way to make unsigned negative variables? I know the word unsigned means "without sign", so also not a minus (-) sign. But I think C++ must provide it.

like image 732
Martijn Courteaux Avatar asked Jun 12 '10 16:06

Martijn Courteaux


People also ask

Can you be unsigned negative?

An unsigned is an integer that can never be negative. If you take an unsigned 0 and subtract 1 from it, the result wraps around, leaving a very large number (2^32-1 with the typical 32-bit integer size).

What happens if you store negative value in unsigned int?

You simply cannot assign a negative value to an object of an unsigned type. Any such value will be converted to the unsigned type before it's assigned, and the result will always be >= 0.

How do you know if unsigned negative?

An unsigned integer can never hold a negative value. If the value of i is negative, then it will be converted to some positive value when you assign it to j . If you want to know whether the value of i is negative, you should test i , not j .

Is unsigned positive or negative?

Unsigned means non-negative The term "unsigned" in computer programming indicates a variable that can hold only positive numbers. The term "signed" in computer code indicates that a variable can hold negative and positive values.


2 Answers

No. unsigned can only contain nonnegative numbers.

If you need a type that only represent negative numbers, you need to write a class yourself, or just interpret the value as negative in your program.

(But why do you need such a type?)

like image 172
kennytm Avatar answered Sep 27 '22 01:09

kennytm


unsigned integers are only positive. From 3.9.1 paragraph 3 of the 2003 C++ standard:

The range of nonnegative values of a signed integer type is a subrange of the corresponding unsigned integer type, and the value representation of each corresponding signed/unsigned type shall be the same.

The main purpose of the unsigned integer types is to support modulo arithmetic. From 3.9.1 paragraph 4:

Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.

You are free, of course, to treat them as negative if you wish, you'll just have to keep track of that yourself somehow (perhaps with a Boolean flag).

like image 22
Brian Neal Avatar answered Sep 24 '22 01:09

Brian Neal