© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

3.  Can we nest structure definitions?

Ans:
 Yes we can nest structure definitions.  

Ex - 1:  What is the output?
typedef struct error{int warning, error, exception;}error;
     main()
    {
        error g1;
        g1.error =1;
        printf("%d",g1.error);
     }
 
Ans:
1

Explanation:
The three usages of name errors can be distinguishable by the compiler at any instance, so valid (they are in different namespaces).
Typedef struct error{int warning, error, exception;}error;
This error can be used only by preceding the error by struct kayword as in:
struct error someError;
typedef struct error{int warning, error, exception;}error;
This can be used only after . (dot) or -> (arrow) operator preceded by the variable
name as in :
g1.error =1;
            printf("%d",g1.error);
                        typedef struct error{int warning, error, exception;}error;
This can be used to define variables without using the preceding struct keyword as in:
error g1;
Since the compiler can perfectly distinguish between these three usages, it is perfectly legal and valid.
 
Note:
This code is given here to just explain the concept behind. In real programming don’t use such overloading of names. It reduces the readability of the code. Possible doesn’t mean that we should use it!

Ex - 2:  What is the output?
main()
{
struct student
{
char name[30];
struct date dob;
}stud;
struct date
        { 
         int day,month,year;
         };
     scanf("%s%d%d%d", stud.rollno, &student.dob.day, &student.dob.month,      &student.dob.year);
}

Ans:
Compiler Error: Undefined structure date

Explanation:

Inside the struct definition of ‘student’ the member of type struct date is given. The compiler doesn’t have the definition of date structure (forward  reference is not allowed in C in this case) so it issues an error.


SLogix Student Projects
bottom