C语言中sizeof的参数是函数名,返回值是什么?

我编写了如下一段代码:

#include<stdio.h>

int bar() {
   printf("bar\n");
   return 0;
}  
int main() {
    printf("%lu\n", sizeof(*bar));
    return 0;
}

在debian7-64bit平台用clang3.0-6.2和gcc4.7.2编译运行均输出1,后来我尝试把sizeof(*bar)改成了sizeof(bar),仍然输出了1,但是改成&bar后输出变成了8.
我猜测sizeof(&bar)输出的应该是函数指针的大小所以是8,那么请问前两种写法输出的是什么呢?

阅读 4.6k
1 个回答

标准里规定, sizeof不能用在function type上.
http://en.cppreference.com/w/cpp/language/sizeof

sizeof cannot be used with function types, incomplete types, or
bit-field glvalues.

但是gcc做了extension,
https://gcc.gnu.org/onlinedocs/gcc/Pointer-Arith.html

In GNU C, addition and subtraction operations are supported on
pointers to void and on pointers to functions. This is done by
treating the size of a void or of a function as 1.

A consequence of this is that sizeof is also allowed on void and on
function types, and returns 1
.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏