#define my_sizeof_one(type) (char *)(&type+1)-(char*)(&type)
int main(void)
{
int answer;
short x = 1;
long y = 2;
float u = 3.0;
double v = 4.4;
long double w = 5.54;
char c = 'p';
uint32_t e = 653;
uint16_t f = 44;
uint64_t g = 2323232;
typedef enum
{
kCountInvalid,
kCountOne,
kCountTwo,
kCountThree,
kCountFour,
}k_count_t;
/* __DATE__, __TIME__, __FILE__, __LINE__ are predefined symbols */
#if 1
printf("Date : %s\n", __DATE__);
printf("Time : %s\n", __TIME__);
printf("File : %s\n", __FILE__);
printf("Line : %d\n", __LINE__);
#endif
/* The size of various types */
printf("The size of int %zu\n", my_sizeof_one(answer));
printf("The size of short %zu\n", my_sizeof_one(x));
printf("The size of long %zu\n", my_sizeof_one(y));
printf("The size of float %zu\n", my_sizeof_one(u));
printf("The size of double %zu\n", my_sizeof_one(v));
printf("The size of long double %zu\n", my_sizeof_one(w));
printf("The size of char %zu\n", my_sizeof_one(c));
printf("The size of enum %zu\n", my_sizeof_one(k_count_t));
printf("The size of uint16_t %zu\n", my_sizeof_one(f));
printf("The size of uint32_t %zu\n", my_sizeof_one(e));
printf("The size of uint64_t %zu\n", my_sizeof_one(g));
return 0;
}
我收到以下错误:
error: expected expression before 'k_count_t'
error: expected expression before 'k_count_t'
出于某种原因,my_sizeof似乎不适用于C中的枚举数据类型。有人可以解释其原因吗?
答案 0 :(得分:3)
问题是您将类型传递给宏,并且宏不适用于类型。因为你不能拿一个类型的地址。
虽然您已命名宏type
的参数,但该名称具有误导性。宏接受变量而不是类型。好吧,严格来说,它接受使用&
运算符可以获取地址的任何内容。请注意,宏的所有其他用途都包含变量。为宏提供类型k_count_t
的变量,编译器会很高兴。
当然,要学习的真正教训是使用sizeof
就像预期的那样。