views:

180

answers:

2

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

  1. What is the output of the program?
  2. Where is ';' terminating the declaration of 'struct st'?

    By ISO IEC 9899 - 1999 specification, declaration should end with a ';'.

        declaration-specifiers init-declarator-listopt ;
    
  3. 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)?

+9  A: 
  1. The output is 10.
  2. There doesn't need to be a semicolon because the whole thing is a function definition.
  3. The structure tag st is declared at global scope and is therefore visible to main.
Greg Hewgill
+1 exactly what I was about to write.
yngvedh
4. GCC is a little more forgiving than I thought.
Tim Post
+5  A: 

Things may be a little clearer if we reformat the code a bit:

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;
}

Thus, the return type of fn() is struct 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 from translation-unit -> top-level-declaration -> function-definition). The struct type is available to main() because you put a struct tag on it (st). Had you written

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

then 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

struct st {
  int a; 
};

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

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