Unsigned negative primitives?

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

+7
c ++ primitive unsigned negative-number
source share
5 answers

Not. unsigned can only contain non-negative numbers.

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

(But why do you need this type?)

+4
source share

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

Range of non-negative values ​​a Signed integer type is a sub-range of the corresponding unsigned integer type and value representation each corresponding signed / unsigned type must be the same.

The main goal of unsigned integer types is to support modulo arithmetic. From clause 3.9.1 of clause 4:

Unsigned unsigned integers must obey the laws of arithmetic modulo 2 n where n is the number of bits in the value representing this particular size integer.

You are free, of course, treat them as negative, if you want, you just need to somehow monitor this yourself (possibly with a Boolean flag).

+2
source share

I think you think this is wrong.

If you need a negative number, you should not declare the variable as unsigned.

If your problem is a range of values ​​and you need one more bit, then you can use a "larger" data type (for example, int 64).

Then, if you use outdated code, creating a new structure may solve your problem, but this is due to your specific situation, C ++ should not handle it.

0
source share

Do not be fooled by the name: unsigned is often misunderstood as non-negative, but the rules for the language are different ... probably the best name would be "bitmask" or "modulo_integer".

If you think unsigned is non-negative, then, for example, implicit conversion rules are completely stupid (why should the difference between two non-negative be non-negative? Why should the addition of a non-negative and an integer be non-negative?).

It is unfortunate that the C ++ standard library itself did not fall into this misunderstanding, because vector.size () is unsigned (absurd if you mean it as the language itself in terms of bitmasks or modulo_integer). This choice for sizes has more in common with the old 16-bit times than with the unsigned one, and in my opinion it was a terrible choice that we still pay as errors.

0
source share

But I think C ++ should provide it.

Why? Do you think C ++ should provide negative negative numbers? This is silly.

Unsigned values ​​in C ++ are defined as non-negative. They even wrap around; not overflow; at zero! (And the same at the other end of the range)

0
source share

All Articles