如何确保两种类型具有相同的尺寸?

eck*_*kes 6 c visual-studio-2005

在我的代码中,我想确保这一点sizeof(a) == sizeof(b).

第一种方法是让预处理器进行检查:

#if (sizeof(a) != sizeof(b))
#  error sizes don't match
#endif
Run Code Online (Sandbox Code Playgroud)

因为而不能编译fatal error C1017: invalid integer constant expression.好的.了解.

接下来尝试:

if(sizeof(a) != sizeof(b)){
  printf("sizes don't match\n");
  return -1;
}
Run Code Online (Sandbox Code Playgroud)

这会导致警告:warning C4127: conditional expression is constant.

现在,我被困住了.是否有一种警告且无错误的方法来确保两个结构ab具有相同的大小?


编辑: 编译器是Visual Studio 2005,警告级别设置为4.

cur*_*guy 6

数组大小错误

// make sure sizeof(a) == sizeof(b):
int size_must_match[sizeof(a) == sizeof(b)];
// will fail if sizeof(a) == sizeof(b) evaluates to 0
// might produce warning: 'size_must_match' is not used 

// to suppress "'size_must_match' is not used", try:
size_must_match[0]; // might produce warning: "statement has no effect"

要么

typedef int size_must_match[sizeof(a) == sizeof(b)];

编译时算法错误

在C++中保证这些常量表达式在编译时由编译器进行评估,我相信在C中也是如此:

// make sure sizeof(a) == sizeof(b):
1 / (sizeof(a) == sizeof(b));
// might produce warning: "statement has no effect"

int size_must_match = 1 / (sizeof(a) == sizeof(b));
// might produce warning: 'size_must_match' is unused

assert (1 / (sizeof(a) == sizeof(b)));
// very silly way to use assert!

开关(只是为了好玩)

switch (0) { // compiler might complain that the 
             // controlling expression is constant
case 0:       
case sizeof(a) == sizeof(b):
    ; // nothing to do
}

你明白了.试试这个,直到编译器100%满意为止.