在所有的C编译器中,复制 case
常量是一个能够保证运行的技巧,无论每个编译器如何报告错误。对于Visual C++来说,它非常简单:
struct X {
int a,b;
int c[10];
};
int _tmain(int argc, _TCHAR* argv[])
{
int dummy;
switch (dummy) {
case sizeof(X):
case sizeof(X):
break;
}
return 0;
}
编译结果:
------ Build started: Project: cpptest, Configuration: Debug Win32 ------
cpptest.cpp c:\work\cpptest\cpptest\cpptest.cpp(29): error C2196: case value '48' already used
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
所以结构体X的大小为48
编辑(2020年6月3日):
对于只打印“重复情况值”的gcc或任何其他编译器,我使用这个技巧来缩小该值:
1)添加一个案例值1==2(表示false)
2)通过试错法,缩小值,例如我尝试猜测sizeof(X)
是否大于16:
#include <stdio.h>
typedef struct _X {
int a;
char b[10];
} X;
int main()
{
printf("Hello World");
int dummy=0 ;
switch (dummy) {
case 1==2:
case sizeof( X)>16:
break;
}
return 0;
}
结果:
main.c: In function ‘main’:
main.c:14:5: error: duplicate case value
case sizeof( X)>16:
^~~~
main.c:13:5: error: previously used here
case 1==2:
所以它是假的,即 sizeof(X)<=16。
3) 使用其他合理的值重复尝试。例如,尝试猜测它是 16,即 sizeof(X)==16
。如果它没有抱怨重复情况值,则该表达式为真。
4) 可选地添加一个case 16
来验证它,例如:
#include <stdio.h>
typedef struct _X {
int a;
char b[10];
} X;
int main()
{
printf("Hello World");
int dummy=0 ;
switch (dummy) {
case sizeof( X):
case 16:
break;
}
return 0;
}
结果
main.c: In function ‘main’:
main.c:15:5: error: duplicate case value
case 16:
^~~~
main.c:14:5: error: previously used here
case sizeof( X):
确认sizeof(X)为16。
另外,观察到gcc可以报告多个重复项,因此这个技巧可以用于在单次遍历中进行多次猜测:
#include <stdio.h>
typedef struct _X {
int a;
char b[10];
} X;
int main()
{
printf("Hello World");
int dummy=0 ;
switch (dummy) {
case 1==2:
case 1==1:
case sizeof( X)>10:
case sizeof( X)>12:
case sizeof( X)>14:
case sizeof( X)>16:
case sizeof( X)==16:
break;
}
return 0;
}
结果
main.c: In function ‘main’:
main.c:14:5: error: duplicate case value
case sizeof( X)>10:
^~~~
main.c:13:5: error: previously used here
case 1==1:
^~~~
main.c:15:5: error: duplicate case value
case sizeof( X)>12:
^~~~
main.c:13:5: error: previously used here
case 1==1:
^~~~
main.c:16:5: error: duplicate case value
case sizeof( X)>14:
^~~~
main.c:13:5: error: previously used here
case 1==1:
^~~~
main.c:17:5: error: duplicate case value
case sizeof( X)>16:
^~~~
main.c:12:5: error: previously used here
case 1==2:
^~~~
main.c:18:5: error: duplicate case value
case sizeof( X)==16:
^~~~
main.c:13:5: error: previously used here
case 1==1:
^~~~
建议 sizeof(X)
大于10、大于12、大于14,但不大于16。加上 ==16 作为最后的猜测。
sizeof
也在编译时评估)。 - mafso