Monday, July 2, 2007

Interesting C Program -2

I thought the following program was a perfect C program. But on compiling, I found a silly mistake. Can you find it out (without compiling the program :-) ?

#include "stdio.h"
#include "stdlib.h"

void OS_Solaris_print()
{
printf("Solaris - Sun Microsystems\n");
}
void OS_Windows_print()
{
printf("Windows - Microsoft\n");
}
void OS_HP-UX_print()
{
printf("HP-UX - Hewlett Packard\n");
}
int main()
{
int num;
printf("Enter the number (1-3):\n");
scanf("%d",&num);
switch(num)
{
case 1:
OS_Solaris_print();
break;
case 2:
OS_Windows_print();
break;
case 3:
OS_HP-UX_print();
break;
default:
printf("Hmm! only 1-3 :-)\n");
break;
}
return 0;
}


The bug is in "OS_HP-UX_print();". The function should not use '-' symbol. It will be considered as a minus. So the compiler will show error as OS_HP has not yet been defined and UX_print has not yet been defined.
Try the following code. The correct version.

#include "stdio.h"
#include "stdlib.h"

void OS_Solaris_print()
{
printf("Solaris - Sun Microsystems\n");
}
void OS_Windows_print()
{
printf("Windows - Microsoft\n");
}
void OS_HP_UX_print()
{
printf("HP-UX - Hewlett Packard\n");
}
int main()
{
int num;
printf("Enter the number (1-3):\n");
scanf("%d",&num);
switch(num)
{
case 1:
OS_Solaris_print();
break;
case 2:
OS_Windows_print();
break;
case 3:
OS_HP_UX_print();
break;
default:
printf("Hmm! only 1-3 :-)\n");
break;
}
return 0;
}

No comments:

Search Google

Books that I refer to...

  • The Complete Reference C, Fourth Edition
  • The C Programming Language