Thursday, 1 March 2012

Frequently Asked Questions in Technical Round at MNCs like TCS, WIPRO, INFOSYS,..etc – 12

Predict the output or error(s) for the following:


1)

int i=10;

main()

{

extern int i;


{


int i=20;


{


const volatile unsigned i=30;


printf("%d",i);


}


printf("%d",i);


}


printf("%d",i);


}

Answer:

30,20,10


Explanation:

'{' introduces new block and thus new scope. In the innermost block i is declared as,


const volatile unsigned


which is a valid declaration. i is assumed of type int. So printf prints 30. In the next block, i has value 20 and so printf prints 20. In the outermost block, i is declared as extern, so no storage space is allocated for it. After compilation is over the linker resolves it to global variable i (since it is the only variable visible there). So it prints i's value as 10.


2)

main()

{

int *j;


{


int i=10;


j=&i;


}


printf("%d",*j);


}

Answer:

10


Explanation:

The variable i is a block level variable and the visibility is inside that block only. But the lifetime of i is lifetime of the function so it lives upto the exit of main function. Since the i is still allocated space, *j prints the value stored in i since j points i.


3)

main()

{

int i=-1;


-i;


printf("i = %d, -i = %d \n",i,-i);


}

Answer:

i = -1, -i = 1


Explanation:

-i is executed and this execution doesn't affect the value of i. In printf first you just print the value of i. After that the value of the expression -i = -(-1) is printed.

No comments:

Post a Comment