INFO: Overflow in Integer Math Expressions Not CheckedLast reviewed: October 3, 1997Article ID: Q38733 |
The information in this article applies to:
SUMMARYThe operations performed by the integer arithmetic and shift operators do not check for overflow or underflow conditions. Information may be lost if the result of an operation cannot be represented in the type of the operands after conversion. All expressions are evaluated prior to assignment to a variable. The compiler will generate the following warning in some cases:
warning C4307: 'operator' : integral constant overflowThis warning is only generated for computations on constants as shown in the example. This is a level 2 warning. Rules for numeric conversion are described in the "Microsoft C Language Reference" manual.
MORE INFORMATIONThe following 3 examples demonstrates the overflow condition for 16-bit compilers:
/* compile options needed: none */ #include <stdio.h> void main(void); void main() { long l; int i = 70; int j = 1000; l = 70 * 1000; /* First Example */ /* C4307 in version 7 and later */ printf( "l = %ld\n", l ); /* l = 4464 = 70000 % 65536 */ /* Overflow not caught!!! */ l = i * j; /* Second Example */ printf( "l = %ld\n", l ); /* l = 4464 = 70000 % 65536 */ /* Overflow not caught!!! */ l = 70L * 1000; /* Third Example */ printf( "l = %ld\n", l ); /* l = 70000 */ /* arithmetic in long--no */ /* overflow */ }In the first two examples, 70 and 1000 are considered as integers. Because both are integer types, integer math is being performed. Integers can have at most a value of 32,767. When 70 is multiplied to 1000, the product exceeds the maximum value that an integer can hold. Overflow is not checked and information is lost. Thus we get a value of 4464, which is 70,000 mod 65,536. The third example is a work around. Conversions occur if the types of the operands are different. Note: 70 is a long integer (32 bits; without the L, it is considered a normal integer of 16 bits). Because a long integer is used, all operands are converted to long and the math is done using 32-bit arithmetic. The product is large enough to handle the multiplication, so the correct result of 70,000 is generated.
|
Additional query words: 8.00 8.00c 9.00
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |