c - 解释 sizeof 运算符应用于函数类型时的输出

标签 c function printf sizeof

以下代码的输出是:

Hello World4

如何?

#include "stdio.h"  

int func()  
{
    return(printf("Hello world"));
}

int main()  
{
    printf("%d",sizeof(fun));
    return 0;  
}

更多引用请查看图片enter image description here

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/

相关文章:

c - C 中的 sprintf 重置计数变量的值

c - C中 "#pragma section <XYZ>"有什么用?

C lib 调用另一个 lib 中的全局变量

RememberMe 的 onSubmit 登录表单中的 JavaScript 超时函数

function - powershell 参数需要在脚本的前面吗?

c - 如果变量不在函数的顶部,则禁用变量声明

c - X 宏破坏 doxygen 调用图

c - 如何使用 PID Controller ?

java - 在 if 语句的第二级之后无法将输出打印到正确的小数点

c - printf ("%s\n",str);给出段错误但 printf ("%s",str);不要,其中 "str"是一个字符串指针