Wednesday, 27 February 2013

C/C++ Puzzles: PART - 23

C/C++ Program Reading Another Program while Compiling

  Recently I have come across a puzzle. The question was to write a C Program which while compiling reads another C program. Well, frankly I had no clue. But later I got some help to solve it. The idea was to use the preprocessor. The first program only has Preprocessor code. 


#define A pgm1
#ifdef A
#warning IGNORE THE WARNING MESSAGE!!! Please Enter the Second C Program
#endif

#include "/dev/stdin"

Click here to download the C Program.

Save program as pgm1.c in Linux and compile as follows, " gcc pgm1.c ". The program waits for user input from keyboard. Type the second program and enter CTRL + D to stop typing. Now run the program as follows " ./a.out ". I have typed the following program while compiling the first program.

#include<stdio.h>

int main( )
{
   int a,b,sum;
   printf("\nEnter Two Numbers:\n");
   scanf("%d%d",&a,&b);
   sum=a+b;
   printf("\nSum = %d\n\n",sum);
}

Figure Below Shows the Output

No comments:

Post a Comment