ViliusRaudys
ViliusRaudys

Reputation: 3

Why my boolean function result is not recognized in main function

so I'm trying to build an ATM program, and I can't really understand why my code isn't working.

code:

#include <stdio.h>
#include <stdbool.h>

bool accessCheck(int);

const int pin =1234;

int main(){
    int code, access;
    printf("Hi, please enter your password:");
    scanf("%d",&code);
    
    accessCheck(code);
    if(accessCheck(code)==1){
        printf("Password recognized.");
    }
    else {
        printf("Password unrecognized.");
    }
    return 0;   
}

bool accessCheck(int x){
    bool access=0;
    if(x == pin){
        bool access = 1;
    }
    return access;
}

Upvotes: 0

Views: 79

Answers (1)

Barmar
Barmar

Reputation: 780843

You're declaring new variable access inside the if block. This shadows the variable with the same name in the main block of accessCheck.

You should just assign that variable rather than declaring another variable.

#include <stdio.h>
#include <stdbool.h>

bool accessCheck(int);

const int pin =1234;

int main(){
    int code;
    printf("Hi, please enter your password:");
    scanf("%d",&code);

    if(accessCheck(code)){
        printf("Password recognized.");
    }
    else {
        printf("Password unrecognized.");
    }
    return 0;
}

bool accessCheck(int x){
    bool access=false;
    if(x == pin){
        access = true;
    }
    return access;
}

Since you're using stdbool you can use true and false instead of 1 and 0.

There's no need to call accessCheck() before the if statement.

Upvotes: 1

Related Questions