Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Why not C++ = avoid negative values by using unsigned types

Shulou Source: shulou.com Published: 2022-06-01 19:48:15 09月29日 Update

This article introduces the knowledge of "Why C++ should not = avoid negative values by using unsigned types". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations! I hope you can read it carefully and be able to achieve something!

ES.106: don't try to avoid negative values by using unsigned types

Reason (reason)

Choosing unsigned numbers means modifying many useless behaviors of integers (such as modular operations), which suppresses overflowing associated warnings and opens the door to errors related to mixed signed / unsigned numbers. Using unsigned numbers does not really eliminate the possibility of negative values.

Example (sample)

Unsigned int U1 =-2; / / Valid: the value of U1 is 4294967294

Int i1 =-2

Unsigned int U2 = i1; / / Valid: the value of U2 is 4294967294

Int i2 = U2; / / Valid: the value of i2 is-2

In real code, the hidden problems in these (perfectly legal) constructs are hard to find and can lead to a lot of real-world errors. Consider the following code:

Unsigned area (unsigned height, unsigned width) {return height*width;} / / [see also] (# Ri-expects)

/ /...

Int height

Cin > > height

Auto a = area (height, 2); / / if the input is-2 a becomes 4294967292

Remember that when-1 is assigned to an unsigned integer, it becomes the largest unsigned integer. At the same time, because the unsigned mathematical operation is calculated according to the module, the multiplication operation will not overflow, but rewind.

Example (sample)

Unsigned max = 1000000; / / "accidental typo", I mean to say 10000000

Unsigned short x = 100

While (x

< max) x += 100; // infinite loop 如果x是一个有符号短整数,我们会收到一个由于溢出而导致无定义行为的警告。 Alternatives(其他选项) use signed integers and check for x >

= 0

Use signed integers and check if x is greater than 0

Use a positive integer type

Use a positive integer type

Use an integer subrange type

Use range-qualified integer types

Assert (- 1 < x)

Use assertion check (- 1)

Tags: Symbols integers types negative values operations numbers examples examples codes content actual more knowledge errors checking legal practical maximum learned and then Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Shulou Technology OPPO Reno MySQL Shulou Information