The Problem of Numerical Overflow in C Language (Part 1)

Question: When will automatic type conversion occur?

    In an assignment statement, when the type of the variable on the left side of the assignment operator is inconsistent with the expression on the right side, automatic type conversion will occur. 

Question: What are the rules for automatic type conversion?

    The type of the expression on the right side of the assignment operator is automatically converted to the type of the expression variable on the left side.

Question: Is it safe to assign values ​​between different types of data?

    

Question: What is a numerical overflow, and why does a numerical overflow occur?

    Any data type can only use a limited number of digits to store data, that is to say, the data expression range of any data type is limited. If we assign data to a variable that exceeds its range, a numerical overflow phenomenon will occur ( This can lead to catastrophic consequences).

Examples of numerical overflow in life:

    

Numerical overflow of integers:

[Note] The data on the right is the result obtained after the program is run.

The difference between signed integer and unsigned integer:

    The highest bit of a signed integer is interpreted as the sign bit (0 -> positive, 1-> negative), while the highest bit of an unsigned integer is interpreted as the data bit.

Overflow of integers:

[Note] The type of the variable a shown in the figure is an unsigned short integer.

[Note] The variable a shown in the figure is interpreted as an unsigned integer in the second line and as a signed integer in the third line.

[Note] The binary data shown in the third line of the yellow area is the complement of -32768, which is artificially specified.

[Note] Negative numbers are stored in the memory in the form of complement.

The value in the process from integer data to short integer data is lost:

[Note] The int type variable occupies 4 bytes in the memory, and the short type variable occupies 2 bytes in the memory.

[Note] The short type variable only retains the lower two bytes of the int type variable.

Two unsigned short integer data are subtracted:

 

Guess you like

Origin blog.csdn.net/weixin_42048463/article/details/115043658