BlackMamba BlackMamba - 1 year ago 52
C++ Question

Confused about the element number is -1 for array

I'm reading a code from here:

But I'm confused about these two lines:

char require_32_bit_integer_at_least[sizeof(int) >= sizeof(int32_t) ? 1 : -1];


(void) require_32_bit_integer_at_least; // no warning please

What's the purpose of them?

char require_32_bit_integer_at_least[sizeof(int) >= sizeof(int32_t) ? 1 : -1];

int getJulianDayNumber(int year, int month, int day)
(void) require_32_bit_integer_at_least; // no warning please
int a = (14 - month) / 12;
int y = year + 4800 - a;
int m = month + 12 * a - 3;
return day + (153*m + 2) / 5 + y*365 + y/4 - y/100 + y/400 - 32045;

Answer Source

The code requires that an int is at least 32 bit wide. If that is not the case and sizeof(int) is less than 32 bit you would get an error like:

error: size of array 'require_32_bit_integer_at_least' is negative

The line

(void) require_32_bit_integer_at_least; // no warning please

seems to be to avoid the "unused variable" warning. However, as the array is not defined as static the compiler would not generate a warning anyhow. Knowing that a global non-static variable is really unused would require checking all translation units (source files) in the entire project.

As proposed by @MartinBonner, to make it clearer and easier to use, we could define a "static assert" macro:

#define STATIC_ASSERT(EXPR, MSG) typedef char static_assertion_##MSG[(EXPR) ? 1 : -1]

and use it as follows:

STATIC_ASSERT(sizeof(int) >= sizeof(int32_t), int_is_less_than_32_bit);    

const bool foo = true;
STATIC_ASSERT(foo, foo_is_not_true); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download