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
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)?
a : a question or problem that requires thought, skill, or cleverness to be answered or solved. a book of puns, riddles, and puzzles.
There are three major types of crossword puzzles: fill-in, hints, and cryptic.
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.
st
is declared at global scope and is therefore visible to main.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 */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With