how to fix the error c2118: negative subscript

Gentoo picture Gentoo · Sep 25, 2009 · Viewed 14.2k times · Source

Again, porting 32-bit app to 64-bit. I get the negative subscript error on the C_ASSERT statement mentioned below..


C_ASSERT (sizeof(somestruct) == some#define);

I also read the http://support.microsoft.com/kb/68475 article but not sure if I know how to fix it in this case.

Help is appreciated.

Thanks in advance.

Answer

Adam Rosenfield picture Adam Rosenfield · Sep 26, 2009

I'm guessing the C_ASSERT macro is defined something like this:

#define C_ASSERT(x) typedef char C_ASSERT_ ## __COUNTER__ [(x) ? 1 : -1];

This is a compile-time assertion: if the compile-time expression x is true, then this expands to something like

typedef char C_ASSERT_1[1];

which declares the typename C_ASSERT_1 to be an alias for the type char[1] (array of 1 char). Converely, if the expression x is false, it expands to

typedef char C_ASSERT_1[-1];

which is a compiler error, since you can't have an array type of negative size.

Hence, your problem is that the expression sizeof(somestruct) == some#define is false, i.e. the size of somestruct is NOT what your code is expecting. You need to fix this -- either change the size of somestruct, or change the value of some#define, making sure that this won't break anything.