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

C and C++ Interview Questions

4. What is the difference between the -> and . operators?

Ans:
They both provide access to members of a structure or union. They differ in that -> is used when the variable is a pointer to a structure or union. The dot is used when the variable is itself the structure or union. The -> operator combines the pointer dereferencing operator with the member access operator; it is syntactic "sugar coating."

Ex - 1:  What is the output?
main()
{
struct date;
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:

Only declaration of struct date is available inside the structure definition of ‘student’ but to have a variable of type struct date the definition of the structure is required.

Ex - 2:  There were 10 records stored in “somefile.dat” but the following program printed 11 names. What went wrong?
void main()
{
struct student
{         
char name[30], rollno[6];
}stud;
FILE *fp = fopen(“somefile.dat”,”r”);
while(!feof(fp))
 {
                        fread(&stud, sizeof(stud), 1 , fp);
puts(stud.name);
}
}

Explanation:

fread reads 10 records and prints the names successfully. It will return EOF only when fread tries to read another record and fails reading EOF (and returning EOF). So it prints the last record again. After this only the condition feof(fp) becomes false, hence comes out of the while loop.


SLogix Student Projects
bottom