以下代码的输出是:
Hello World4
如何?
#include "stdio.h"
int func()
{
return(printf("Hello world"));
}
int main()
{
printf("%d",sizeof(fun));
return 0;
}
P.S :- 据我所知,sizeof() 调用 func() 函数,其中返回语句调用 printf 函数,打印 hello world 并返回字符串长度,即 11 到返回函数,然后 sizeof() 函数返回的大小11 是 int,int 的值取决于编译器 2 或 4
最佳答案
sizeof
运算符不能应用于函数。
来自C11草案,6.5.3.4 sizeof和alignof运算符
The sizeof operator shall not be applied to an expression that has function type or an incomplete type, to the parenthesized name of such a type, or to an expression that designates a bit-field member.
因此,根据 C 标准,您所做的违反了约束。
使用-std=c11
编译,gcc产生警告:
$gcc -std=c11 -Wall -pedantic-errors s.c
test.c: In function ‘main’:
s.c:10:23: error: invalid application of ‘sizeof’ to a function type [-Wpointer-arith]
printf("%d",sizeof(func));
^
test.c:10:12: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]
printf("%d",sizeof(func));
如您所见,还有另一个问题。您不能使用 %d
来打印 size_t
。 %zu
是打印 size_t
的正确格式说明符。
关于c - 解释 sizeof 运算符应用于函数类型时的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37939067/