In my code, I want to ensure that sizeof(a) == sizeof(b).
First approach was to let the preprocessor do the checking:
#if (sizeof(a) != sizeof(b))
# error sizes don't match
#endif
which doesn’t compile because of fatal error C1017: invalid integer constant expression. Okay. Understand.
Next try:
if(sizeof(a) != sizeof(b)){
printf("sizes don't match\n");
return -1;
}
Which results in a warning: warning C4127: conditional expression is constant.
Now, I’m stuck. Is there a warning-and-error-free way to make sure that the two structs a and b have the same size?
Edit:
Compiler is Visual Studio 2005, Warning level is set to 4.
Bad array size
or
Bad compile-time arithmetic
In C++ is guaranteed that these constant expressions are evaluated by the compiler at compile-time, and I believe the same holds in C:
Switch (just for fun)
switch (0) { // compiler might complain that the // controlling expression is constant case 0: case sizeof(a) == sizeof(b): ; // nothing to do }You get the idea. Just play around with this until the compiler is 100 % happy.