Tuesday, March 13, 2012

Find the output of the following code snippets.


Snippet 1:

int get()
{
    int a[4]={10,20,30,40};
    int *p = &a[2];
    return (p[-1]);
}

main()
{
    int x=get();
    printf("x value is %d\n",x);
}

OutPut:
x value is 20

Explaination: Internal memory is like shown in the picture. P is pointed to the a[2]. So starting value for P is 30.As P is a pointer , we can move back and forth using index or by incrementing the pointer. P[-1] is 20 and p[-2 ] is 10. And P[-3 ] is not defined as the memry is not specified.  And we are returning a value and not a address. So there is no problem of returning the values.
Snippet 2:

class C{
public:
    C()
    {
        cout<<"this is constructor"<<endl;
    }
    ~C()
    {
        cout<<"this is destructor"<<endl;
    }
};
int main()
{
    C c;
    exit(0);
}


OutPut:
this is constructor

Explaination: Genarally, instantiating Class will create Constructor and while exiting it will call destructor. So expected output should be displaying constructor and destructor messages. But Because of the exit() function call, destructor will not call. exit function  calls before the destructor call. If you use anywhere in the application , need to call the destructor manually.

Snippet 3:

class base{
public:
    void display()
    {
        cout<<"base dispaly function"<<endl;
        func();
    }
    virtual void func()  
    {
        cout<<"base func function"<<endl;
    }
};
class derived: public base{
public:
    void func()
    {
        cout<<"derived func function"<<endl;
    }
};
main()
{
    derived d;
    d.display();
}


OutPut:
base dispaly function
derived func function

Explaination: There is a class base with two member functions display() and func() in which func() is a virtual. display() method calls func() in the definition. There is a derived class from the base , in which only func() definition is there in the derived class. If you try to call the display() function from the main as in the code snippet , we will get the above output. This is because of function overriding. Also called late or runtime binding. If you not use virtual  keyword, you will get only base method definitions.

Snippet 4:

struct s1
{
    int x,y;
};
struct s2
{
    int m,n,o;
};
main()
{
    struct s1 S1;
    S1.x=10;
    S1.y=20;
    struct s2 *S2;
    S2=&S1;
    printf("S2->m is %d\n",S2->m);
    printf("S2->n is %d\n",S2->n);
}

OutPut:
S2->m is 10
S2->n is 20

Explaination: Generally you will get the warning message while compilation. If you ignore warning message(as a developer, should not ignore the warnings :-)), we will get the above output. As it is handling with memory. Address of  S1 is assigned to S2. Now we can access using S2. If the memory allignment is fine(i.e data types are similar), it works fine(in our example). Other wise behaviour is undefined.

No comments:

Popular Posts