Home > Enterprise >  C variable undeclared
C variable undeclared

Time:01-18

I'm trying to make a program in C were you have to guess a random number. I made an if statement that checks if the input matches the answer but the int I made the answer says it's undeclared.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int myNum;

void An() {
    if (myNum == anNum) {
        printf("Correct! \n\n");
    } else {
        printf ("Wrong guess again \n");
        guess();
    }     
}

void guess () {
    scanf("%d", &myNum);
    An(); 
}

int main () {

    int anNum = (rand() % 10)   1;

    printf("%d", anNum);
    srand(time(0));
    printf("Guess the number from 1-10! \n");
    guess();
     
    return 0;
}

I tried declaring the variable in the header but that didn't work and I tried making a separate function but that also didn't work

CodePudding user response:

anNum is a local variable inside your main() function, and it is not visible to An(). You should pass this variable from main() to guess() first, and then pass it to An(), like so:

void An(int anNum) {
    if (myNum == anNum)
    {
        printf("Correct! \n\n");
    } else {
        printf ("Wrong guess again \n");
        guess(anNum);
    }     
}

void guess (int number) {
    scanf("%d", &myNum);
    An(number); 
}

int main () {

    int anNum = (rand() % 10)  1;

    printf("%d", anNum);
    srand(time(0));
    printf("Guess the number from 1-10! \n");
    guess(anNum);
     
    return 0;
}

In C, everything that is declared inside curly brackets { } is local to that scope, so you can only use local variables in other functions by passing it to them.

CodePudding user response:

The variable anNum should be declared either globally or in the function where it has been used. So, in order to rectify your error you need to pass anNum to guess() function then again you have to pass anNum from guess() to An() function by using arguments.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int myNum;

//For the below function You have to declare the function with the respective data type here in this case is 'int' because of the arguments we have used.//

int An(a,b) 
{
    if(a==b)
    {
        printf("Correct! \n\n");
    } 
    else {
        printf ("Wrong guess again \n");
        guess(b);
    }     
}

    int guess (x) {
    int anNum=x;
    int myNum;
    scanf("%d", &myNum);
    An(myNum,anNum); 
}

int main () {
    srand(time(0));

//Here srand(time(0)) should be used before random number generation

    int anNum = rand() % 10   1;    
    printf("%d\n", anNum);
    printf("Guess the number from 1-10! \n");
    guess(anNum);
    return 0;
}
  •  Tags:  
  • c
  • Related