我打了个代码sizeof返回零了,求解。
代码:
long long int a=3;
printf("%ld,%d\n",a,sizeof(a));
编译警告:
warning: format ‘%ld’ expects type ‘long int’, but argument 2 has type ‘long long int’
运行结果:
3,0
如果将第一个%ld按警告改为%lld则无警告,运行结果就是3,8为什么呢?
ubuntu gcc编译器,
gcc --version
gcc (Ubuntu/Linaro 4.4.4-14ubuntu5.1) 4.4.5
In a declarationT D where D has the form
D1 [constant-expressionopt]
and the type of the identifier in the declarationT D1 is “derived-declarator-type-list T,” then the type of the
identifier of D……
[/Quote]
In a declarationT D where D has the form
D1 [constant-expressionopt]
and the type of the identifier in the declarationT D1 is “derived-declarator-type-list T,” then the type of the
identifier of D is an array type.
If the constant-expression
(5.19) is present, it shall be an integral constant expression and its value shall be greater than zero.
Is it possible for the sizeof operator to ever return 0 (zero) in C or C++? If it is possible, is it correct from a standards point of view?
Answer:
In C++ an empty class or struct has a sizeof at least 1 by definition. From the C++ standard, 9/3 "Classes": "Complete objects and member subobjects of class type shall have nonzero size."
In C an empty struct is not permitted, except by extension (or a flaw in the compiler).
This is a consequence of the grammar (which requires that there be something inside the braces) along with this sentence from 6.7.2.1/7 "Structure and union specifiers": "If the struct-declaration-list contains no named members, the behavior is undefined".
If a zero-sized structure is permitted, then it's a language extension (or a flaw in the compiler). For example, in GCC the extension is documented in "Structures with No Members", which says:
GCC permits a C structure to have no members:
struct empty {
};
The structure will have size zero. In C++, empty structures are part of the language. G++ treats empty structures as if they had a single member of type char.