Duplicate case 常量是保证在所有 C 编译器中都能工作的技巧,无论它们如何报告错误。对于 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)添加一个case值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:
//case 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)
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 1==2:
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: //represents false
case 1==1: //represents true
case sizeof( X)>10:
case sizeof( X)>12:
case sizeof( X)>14:
case sizeof( X)>16:
case sizeof( X)==16:
//case 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 作为最终猜测。