C拼图 - 玩类型

Gan*_*ian 9 c puzzle types scope declaration

请检查以下程序.

#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) ;
}
Run Code Online (Sandbox Code Playgroud)

以下是问题

  1. 该计划的输出是什么?
  2. 哪里 ';' 终止'struct st'的声明?

    根据ISO IEC 9899-1999规范,声明应以';'结尾.

        declaration-specifiers init-declarator-listopt ;
    
    Run Code Online (Sandbox Code Playgroud)
  3. 如果'struct st'的声明仅代表函数'fn'的返回类型,那么它对其他函数(main)的可见性如何?

Gre*_*ill 9

  1. 输出为10.
  2. 不需要分号,因为整个事物是函数定义.
  3. 结构标记st在全局范围内声明,因此对main可见.


Joh*_*ode 5

如果我们重新格式化代码,情况可能会更清楚一些:

struct st { int a; } fn() 
{
  struct st obj;
  obj.a = 10;
  return obj;
}
int main()
{
  struct st obj = fn();
  printf("%d\n", obj.a);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

因此,返回类型fn()struct st {int a;}.在struct定义之后没有分号,因为struct类型是函数定义的一部分(从translation-unit- > top-level-declaration- > 跟踪语法function-definition).结构类型可用,main()因为你在它上面放了一个struct标签(st).如果你写的

struct { int a; } fn() {...}
Run Code Online (Sandbox Code Playgroud)

然后该类型将无法使用main(); 你将不得不创建一个具有相同定义的新结构类型.

你得到的效果就像你写的一样

struct st {
  int a; 
};

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

int main()
{
  /* same as before */
}
Run Code Online (Sandbox Code Playgroud)