C 拼图 - 玩类型
请检查以下程序。
#include <stdio.h>
struct st
{
int a ;
}
fn ()
{
struct st obj ;
obj.a = 10 ;
return obj ;
}
int main()
{
struct st obj = fn() ;
printf ("%d", obj.a) ;
}
以下问题是
- 程序的输出是什么?
“;”在哪里终止“struct st”的声明?
通过 ISO IEC 9899 - 1999 规范、声明应 以“;”结尾。
声明说明符 init-declarator-listopt ;
如果 'struct 的声明 st' 只代表返回类型 函数“fn”,它是如何可见的 到其他函数(主函数)?
Please check the below program.
#include <stdio.h>
struct st
{
int a ;
}
fn ()
{
struct st obj ;
obj.a = 10 ;
return obj ;
}
int main()
{
struct st obj = fn() ;
printf ("%d", obj.a) ;
}
Following are the questions
- What is the output of the program?
Where is ';' terminating the declaration of 'struct st'?
By ISO IEC 9899 - 1999
specification, declaration should
end with a ';'.declaration-specifiers init-declarator-listopt ;
If the declaration of the 'struct
st' is taken representing only the return type of
the function 'fn', how is it visible
to other functions (main)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
st
是在全局范围内声明的,因此对 main 可见。st
is declared at global scope and is therefore visible to main.如果我们重新格式化一下代码,事情可能会更清楚一些:
因此,
fn()
的返回类型是struct st {int a;}
。结构体定义后没有分号,因为结构体类型是函数定义的一部分(从translation-unit
->top-level-declaration
-> 跟踪语法;函数定义
)。结构类型可用于main()
因为您在其上放置了一个结构标记 (st)。如果你这样写,那么该类型将无法被
main()
使用;您必须创建具有相同定义的新结构类型。你得到的效果和你写的一样
Things may be a little clearer if we reformat the code a bit:
Thus, the return type of
fn()
isstruct st {int a;}
. There's no semicolon after the struct definition because the struct type is part of the function definition (trace through the grammar fromtranslation-unit
->top-level-declaration
->function-definition
). The struct type is available tomain()
because you put a struct tag on it (st). Had you writtenthen the type would not have been available to
main()
; you would have had to create a new struct type with the same definition.You get the same effect as if you had written