Thursday, August 5, 2010

Interview qeustions on C/C++

1. What is the size of the structure, assume int to be 4 bytes and float to be 4 bytes.

struct {
    enum  {
        integer,
        floating
    } type;
    union {
        int a;
        float b;
    };
} t1;

Answer: The enum would take one integer (4) and other union together will take one more space of larget between two (4), so total 8 bytes.

suppose the structure delcaration is changes as below, then what would be the size?

struct {
    enum type {
        integer,
        floating
    } ;
    union {
        int a;
        float b;
    };
} t1;

Answer: This would result in compilation error, as there is no member of 'type'

2. What doe the following function do? can it be given a better name?

DT* func(DT* a, const DT* b)
{
    DT *c = a;
    while(*a++ = *b++);
    return c;
}

Answer: Assuming that DT is an integer or char, the function would copy data from b to a, untill a zero in b is obtained, zero is also copied, so it can be renamed as string copy function.

3. Is the out put of line one and two inside the loop same, or different?

int a[100][100];
for(int i = 0; i<100; i++) {
    for(int j = 0; j<100; j++) {
        printf("%d", a[i][j]);
        printf("%d", a[j][i]);
    }
}

Answer: The output would be different as they refer to different row and colum, but at the end they out put all the data in the two dimentional array.

If one needs to be prefered over the other, which one will you prefer? and why?

Answer: The first one will be faster as it has less cache miss in case of a cache enabled system compared to the second one, so in a practical system the using first line would be faster, and so it should be prefered. Theoretically if memory access does not use cache, then both will be same in terms of time taken.

4. What is function overloading? how does compiler will know which function to call?

class{ 
    void func(int a);
    void func(int a, int b);
}

Answer: Having many function definitions for the same functions with different number of arguments is called function overloading, and the compiler will decide about the functions by seeing the type and number of params passed to the function call, and decide on which function to call at compile time.

Suppose if the function is defined below with a default argument and when calling if it is not passed then how would compiler decide about function?

class{ 
    void func(int a);
    void func(int a, int b = 0);
}

Answer: Then the compiler wont be able to decide, and it will throw a compile time error.

No comments:

Post a Comment