Using sizeof operator on a typedef-ed struct

匿名 (未验证) 提交于 2019-12-03 03:06:01

问题:

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!

回答1:

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 be sizeof (tmp).

As in

if (c <= sizeof tmp) should be if (c <= sizeof (tmp)).

Yup, pretty "obvious and straightforward".



回答2:

The sizeof operator have two forms:

sizeof expression sizeof(type)

As you're giving it a type, you need the parenthesis, sizeof(tmp)



回答3:

add parentheses around tmp: sizeof(tmp)



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!