加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C拼图 – 玩的类型

发布时间:2020-12-16 03:34:25 所属栏目:百科 来源:网络整理
导读:请检查以下程序. #include stdio.hstruct 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 – 199
请检查以下程序.
#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
规格,声明应
以’;’结尾.

declaration-specifiers init-declarator-listopt ;

>如果声明“struct”
st’仅代表返回类型
函数’fn’,它是如何可见的
到其他功能(主)?

解决方法

如果我们重新格式化代码,事情可能会更清楚一些:
struct st { int a; } fn() 
{
  struct st obj;
  obj.a = 10;
  return obj;
}
int main()
{
  struct st obj = fn();
  printf("%dn",obj.a);
  return 0;
}

因此,fn()的返回类型是struct st {int a;}.在struct定义之后没有分号,因为struct类型是函数定义的一部分(通过翻译单元的语法跟踪 – >顶级声明 – > function-definition).结构类型可用于main(),因为它在其上放置了一个struct标签(st).如果你写的

struct { int a; } fn() {...}

那么该类型将不可用于main();您将不得不使用相同的定义创建一个新的结构体类型.

你得到的效果和你写的一样

struct st {
  int a; 
};

struct st fn() 
{ 
  /* same as before */
}

int main()
{
  /* same as before */
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读