在gcc编译器中,
sizeof(main)
、sizeof(printf)
和sizeof(scanf)
的大小都是1。我想知道这些都为什么会是1,背后的逻辑是什么?由于C(99)标准要求(§6.5.3.4/1)
sizeof
运算符不能用于具有函数类型或不完整类型的表达式,括号中带有这种类型的名称,或指定位域成员的表达式。
因此,返回值毫无意义。如果您需要函数指针的sizeof
,请使用
sizeof(&main)
sizeof(&printf)
sizeof(&scanf)
对于那些 sizeof 无意义的类型,gcc 返回值为1(参见 c-common.c):
4187 if (type_code == FUNCTION_TYPE)
4188 {
4189 if (is_sizeof)
4190 {
4191 if (complain && (pedantic || warn_pointer_arith))
4192 pedwarn (loc, pedantic ? OPT_pedantic : OPT_Wpointer_arith,
4193 "invalid application of %<sizeof%> to a function type");
4194 else if (!complain)
4195 return error_mark_node;
4196 value = size_one_node;
4197 }
4198 else
4199 value = size_int (FUNCTION_BOUNDARY / BITS_PER_UNIT);
4200 }
4201 else if (type_code == VOID_TYPE || type_code == ERROR_MARK)
4202 {
4203 if (type_code == VOID_TYPE
4204 && complain && (pedantic || warn_pointer_arith))
4205 pedwarn (loc, pedantic ? OPT_pedantic : OPT_Wpointer_arith,
4206 "invalid application of %qs to a void type", op_name);
4207 else if (!complain)
4208 return error_mark_node;
4209 value = size_one_node;
4210 }