在typedef-ed结构体上使用sizeof运算符 [英] Using sizeof operator on a typedef-ed struct
问题描述
这可能是太明显了。但是,我找不到具体的答案,虽然许多stackoverflow线程谈论这方面的不同方面。
typedef struct _tmp {
unsigned int a;
unsigned int b;
} tmp;
int main()
{
int c = 10;
if(c <= sizeof tmp){
printf(less\\\
);
} else {
printf(more\\\
);
}
return 0;
}
我将此编译为 -
g ++ -lstdc ++ a.cpp
得到一个错误 -
预期的主表达式')'token
pre>
我想我缺少一些非常明显和直接的东西。但是似乎无法确定: - /
谢谢!
解决方案
5.3.3 Sizeof [expr.sizeof]
1)
sizeof
运算符产生其操作数的对象表示中的字节数。操作数是
,这是一个未求值的操作数(第5条),或带括号的 type-id 。
在您的情况下,它是一个 type-id ,因此必须括号括起来。在 8.1类型名称[dcl.name] 中描述了一个type-id。
sizeof tmp
应为
sizeof(tmp)
。
如
if(c <= sizeof tmp)
应该if(c <= sizeof(tmp) code>。
Yup,非常明显且直接。
This might be something too obvious. However, I couldn't find the specific answer though many stackoverflow threads talk about different aspects of this.
typedef struct _tmp { unsigned int a; unsigned int b; } tmp; int main() { int c=10; if (c <= sizeof tmp) { printf("less\n"); } else { printf("more\n"); } return 0; }
I compile this prog as -
g++ -lstdc++ a.cpp
I get an error -
expected primary-expression before ‘)’ token
I think I am missing something very obvious and straightforward. But can't seem to pinpoint it :-/
Thanks!
解决方案5.3.3 Sizeof [expr.sizeof]
1) The
sizeof
operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is an unevaluated operand (Clause 5), or a parenthesized type-id. (emphasis mine)In your case, it is a type-id so it must be parenthesized. What a type-id is is described in 8.1 Type names [dcl.name].
sizeof tmp
should besizeof (tmp)
.As in
if (c <= sizeof tmp)
should beif (c <= sizeof (tmp))
.Yup, pretty "obvious and straightforward".
这篇关于在typedef-ed结构体上使用sizeof运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!