C/C++ puzzles are regularly asked in all the tests conducted for Computer Science students. GATE, Technical round of a job interview, Test for PhD admission what ever is the nature of the test being conducted there will be C/C++ puzzles. Many often what we think absolutely impossible becomes utterly convincing once the logic is explained. Here I have included some puzzles which are repeatedly asked in various tests. I have compile the programs using Code::Blocks 10.05. So if you use a different compiler some of the program's output may differ. But most of the programs will show the same output irrespective of the compiler used.
main( ) is also a Function
What will be the Output of the program given below.
int i=0;
int main()
{
printf("\nHello");
i++;
if(i<10)
main();
return 0;
}
Download
The Figure Shows the Output of the Program
The program will print Hello exactly 10 times. Because the Global variable i is common for all the main( ) function being called.
Now Consider the modified program given below.
#include<stdio.h>
int main()
{
int i=0;
printf("\nHello");
i++;
if(i<10)
main();
return 0;
}
int main()
{
int i=0;
printf("\nHello");
i++;
if(i<10)
main();
return 0;
}
You will get an infinite loop. Why? The variable i is not Global. Each main( ) function will have its own copy of the variable i. So the value of i never becomes greater than 10.
Now consider another modified version of the program.
#include<stdio.h>
static int main()
{
int i=0;
printf("\nHello");
i++;
if(i<10)
main();
return 0;
}
Download
You will get an error. Why? The main( ) can not precede with a static keyword. But remember main( ) can precede with an extern keyword.
You will get an error. Why? The main( ) can not precede with a static keyword. But remember main( ) can precede with an extern keyword.
No comments:
Post a Comment