PRB: C2118: Negative Subscript May Be Caused by int Expression (68475)
The information in this article applies to:
- Microsoft C for MS-DOS
- Microsoft C for OS/2
- Microsoft Visual C++ for Windows, 16-bit edition 1.0
- Microsoft Visual C++ for Windows, 16-bit edition 1.5
- Microsoft Visual C++ for Windows, 16-bit edition 1.51
- Microsoft Visual C++, 32-bit Editions 1.0
- Microsoft Visual C++, 32-bit Editions 2.0
- Microsoft Visual C++, 32-bit Editions 2.1
- Microsoft Visual C++, 32-bit Editions 4.0
- Microsoft Visual C++, 32-bit Editions 5.0
This article was previously published under Q68475 SYMPTOMS
The compiler error:
C2118: negative subscript
C2118: negative subscript or subscript is too large
may be caused by an integer expression in the subscript of an array. If the
expression evaluates to greater than INT_MAX, as defined in limits.h, its
value becomes negative, thus causing the aforementioned error. For the 16-
bit compilers, INT_MAX equals 32767; for 32-bit compilers, INT_MAX equals
2,147,483,647.
CAUSE
This is correct and expected behavior for the Microsoft C Compiler because
the evaluation of integer expressions is done using integer math. In some
cases, integer math produces an incorrect result because the value of the
expression is larger than an integer.
RESOLUTION
16-bit: To work around this situation, add an uppercase (or lowercase) "L"
to one of the terms of the expression. This will force the compiler to
evaluate the expression using long math which is less likely to overflow.
32-bit (or 16-bit expressions greater than LONG_MAX): Unfortunately, the
above resolution will not work as INT_MAX equals LONG_MAX. In these cases,
we recommend that the array be broken into several smaller arrays, each of
whose size will not exceed INT_MAX.
Modification Type: | Minor | Last Reviewed: | 7/5/2005 |
---|
Keywords: | kbCompiler kbprb KB68475 |
---|
|