Reputation: 13
The code idea is to read the single characters from standard input. In case "y", or "n" was read, the program should print "YES!", or "NO!", respectively.
I tried to use #define
directives within an if
block:
#include <stdio.h>
#include <stdbool.h>
#define YES y
#define NO n
int main()
{
char letter = ' ';
printf("for Yes enter : y\nfor No enter : n\n");
letter = getchar();
if (YES == letter)
{
printf("YES!");
}
else if (NO == letter)
{
printf("NO!");
}
else
{
printf("this option is not available");
}
printf("FUZZY");
getchar();
return 0;
}
This results in the following error:
Ex1.c: In function 'main':
Ex1.c:5:13: error: 'y' undeclared (first use in this function)
#define YES y
^
Ex1.c:13:5: note: in expansion of macro 'YES'
if(YES == letter)
^~~
Ex1.c:5:13: note: each undeclared identifier is reported only once for each function it appears in
#define YES y
^
Ex1.c:13:5: note: in expansion of macro 'YES'
if(YES == letter)
^~~
Ex1.c:6:12: error: 'n' undeclared (first use in this function)
#define NO n
^
Ex1.c:17:10: note: in expansion of macro 'NO'
else if(NO == letter)
What's to do to and make this code work?
Upvotes: 1
Views: 98
Reputation: 669
First ,you should remove #include <stdbool.h>.
Second ,in your defines ,you declare y and x as a variables not as caracters ,to declare as a caracter you should make like this: 'x' , 'y'
#include <stdio.h>
#define YES 'y'
#define NO 'n'
int main()
{
char letter = ' ';
printf("for Yes enter : y\nfor No enter : n\n");
letter = getchar();
if(YES == letter)
{
printf("YES!");
}
else if(NO == letter)
{
printf("NO!");
}
else
{
printf("this option is not available");
}
printf("\nFUZZY");
getchar();
return 0;
}
Upvotes: 0
Reputation: 2567
Reason for "undeclared" error : After pre-processing stage if
statements will become as :
if(YES == letter)
changes to if(y == letter)
else if(NO == letter)
changes to else if(n == letter)
These two statements are the input to the compilation stage, after pre-processing. Clearly, y
and n
variables are not declared. Hence, the error.
Solution :
#define YES 'y'
#define NO 'n'
After these changes if
statements will be (after pre-processing stage):
if(YES == letter)
changes to if('y' == letter)
else if(NO == letter)
changes to else if('n' == letter)
Here, 'y'
and 'n'
are character constatns, not variables. So, you will not get "undeclared" error.
Upvotes: 3