Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Puzzle - play with types

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)?

like image 963
Ganesh Gopalasubramanian Avatar asked Nov 13 '09 09:11

Ganesh Gopalasubramanian


People also ask

What is a puzzle and examples?

a : a question or problem that requires thought, skill, or cleverness to be answered or solved. a book of puns, riddles, and puzzles.

How many types of major puzzles are there?

There are three major types of crossword puzzles: fill-in, hints, and cryptic.

What are puzzles in programming?

Puzzles are a realistic way of testing your lateral thinking in software engineer interviews. It shows the interviewer your real-world problem-solving and creative thinking skills. These puzzles are mostly popular among Tier-1 companies, which look for candidates with more than basic programming skills.


2 Answers

  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.
like image 137
Greg Hewgill Avatar answered Oct 20 '22 10:10

Greg Hewgill


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 */
}
like image 38
John Bode Avatar answered Oct 20 '22 10:10

John Bode