想问一下sizeof一个函数的输出值是多少?
#include
void test()
{
printf("hello, world!\n");
}
int main(void)
{
printf("%ld\n", sizeof(test));
return 0;
}
以上程序的运行结果是1,想问一下是什么原因?
sizeof 的操作数不能是函数
sizeof
运算符不能用于函数类型,另外sizeof
的结果始终是非零的,故gcc编译器返回的是1
gcc/clang编译器可以通过-pedantic
编译选项对上面代码给出警告
$ gcc -pedantic main.c
main.c: In function ‘main’:
main.c:10:26: warning: invalid application of ‘sizeof’ to a function type [-Wpointer-arith]
printf("%d\n", sizeof(test));
^
参考
https://en.cppreference.com/w/cpp/language/sizeof
sizeof cannot be used with function types, incomplete types, ...
The result of sizeof is always nonzero, even if applied to an empty class type.