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

C and C++ Interview Questions

5. Is there a way to compare structures automatically?

Ans:

No. There is no single, good way for a compiler to implement implicit structure comparison (i.e. to support the == operator for structures) which is consistent with C's low-level flavor.

A simple byte-by-byte comparison could founder on random bits present in unused "holes" in the structure (such padding is used to keep the alignment of later fields correct; A field-by-field comparison might require unacceptable amounts of repetitive code for large structures.

If you need to compare two structures, you'll have to write your own function to do so, field by field. 

Ex - 1:  Is the following code legal?
struct a
    {
int x;
 struct a b;
    }

Ans:
No

Explanation:

Is it not legal for a structure to contain a member that is of the same type as in this case. Because this will cause the structure declaration to be recursive without end.

Ex - 2:  Is the following code legal?
main()
{
struct xx
{
int x;
struct yy
{
char s;
            struct xx *p;
};
struct yy *q;
};
}

Ans:
Compiler Error

Explanation:

The structure yy is nested within structure xx. Hence, the elements are of yy are to be accessed through the instance of structure xx, which needs an instance of yy to be known. If the instance is created after defining the structure the compiler will not know about the instance relative to xx. Hence for nested structure yy you have to declare member.


SLogix Student Projects
bottom