A small piece of code to see if it can be done right?
This code is run on a 64-bit machine. You need to enable the 64-bit switch during compilation.
In 64-Bit mode, sizeof (long) = 8, sizeof (INT) = 4. The following examples are obviously reproduced.
/* Test. c
* A simple test code for Overflow
*/
# Include <stdio. h>
Int main (INT argc, char ** argv)
{
Unsigned char Uca, UCB;
Unsigned short USC;
Unsigned int uid, uie;
Unsigned long Ulf;
Unsigned long ulg;
UCA = 128;
U cb = 128;
USC = Uca + UCB;
Uid = 2147483648; // 2G
Uie= 2147483648;
Ulf = uid + uie;
Ulg = 6*1024*1024*1024; // 6g
Printf ("% d, % lu, % lu", USC, Ulf, ulg );
}
What are the results?
The USC value is 256.
Ulf: 0
Ulg: undetermined
The principle is simple. This is the implicit type conversion of the compiler. On the one hand, it is converted from low-precision to high-precision, and on the other hand it is overflow.
It is normal that USC does not overflow, because it forcibly converts Char/unsigned char to int type.
Second, overflow. Because the integer type can only be 4g-1 at the maximum. When the UID is assigned a value, overflow occurs. The UID only captures the lowest 32 bits, that is, 32 zeros.
Third, it is also overflow! This is very concealed.
Ulg = integer * integer
The right side of the value assignment number is a multiplication of four integer types. The Compiler does not forcibly convert the expression on the right of the value assignment number. Therefore, the final result is an integer.
It's off!
However, I found on the machine that the ulg value is not necessarily set to 0, because other content is provided for the 32-bit high. That's strange. Verify it again.
I did not expect that, after so long, the first basic knowledge of freshman year was still vulnerable. A recent bug is the third problem. At that time, I was positioning for a while, and I was puzzled. I didn't expect it to be such a small problem. In the past, I always thought that many C language tests were too detailed, but the bugs caused by these details were the most difficult to find.