Mickeym0use_
Mickeym0use_

Reputation: 13

Defining variables inside if-statement

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

Answers (3)

asemr.
asemr.

Reputation: 1

You should take y and n like character 'y' and 'n'

Upvotes: 0

MED LDN
MED LDN

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

Krishna Kanth Yenumula
Krishna Kanth Yenumula

Reputation: 2567

Reason for "undeclared" error : After pre-processing stage if statements will become as :

  1. if(YES == letter) changes to if(y == letter)

  2. 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):

  1. if(YES == letter) changes to if('y' == letter)

  2. 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

Related Questions