Home > Software engineering >  Turn a function to output a 1 or 0 to be used as a check inside main
Turn a function to output a 1 or 0 to be used as a check inside main

Time:02-10

I have included a part of the code to demonstrate what I attempt to do. The idea is to create a function that can be used as a validation of whether a number is valid and that function to be used inside main. Therefore what I have written in the function e.g the message of whether a day is valid or not, should only return instead a 1 if the day is valid and a zero when a day is invalid.

struct example {
    int day;
    int month;
    int year;
};

Above is the struct:

#include <stdio.h>
int checkday();

int main() {
   if checkday() == 1
       print("%d is valid  date.\n", ex.day)
    return 0;
}

I have written the code below to be used as a check for whether a day is valid or not. And I am thinking of returning 1 if it is valid or 0 if it is not. Then, inside main I will use this function for this purpose and then I will print the relevant message (if it is valid or not) from inside main.

The problem is that if I keep only the cases that check if it is valid and then make it reuturn 1, then how it will work for the cases that the date is invalid.

int checkday(){
    struct example ex;
    if((ex.day>=1 && ex.day<=3) && (ex.month==1 || ex.month==3))
        printf("%d is valid  date.\n", ex.day);
    else if((ex.day>=1 && ex.day<=12) && (ex.month==4 || ex.month==6))
        printf("%d is valid  date.\n", ex.day);
    else
        printf("%d is invalid date.\n", ex.day);
}

CodePudding user response:

You probably need to get the struct as a parameter to the function, it doesn't make sense to use a function otherwise. You should also use the return statement instead of printing.

int checkday(struct example ex){
    if ((ex.day>=1 && ex.day<=3) && (ex.month==1 || ex.month==3)) || 
       ((ex.day>=1 && ex.day<=12) && (ex.month==4 || ex.month==6))
        return 1;
    return 0;
}

Then use:

int main() {
    ....
    if checkday(ex)
        print("%d is valid  date.\n", ex.day);
    return 0;
}

CodePudding user response:

In the first if you can evaluate if your date is valid (I followed your logic), if the if statement is false, return 0 (not valid day)

Maybe you can try this:

int checkday(){
    struct example ex;
    if(((ex.day>=1 && ex.day<=3) && (ex.month==1 || ex.month==3)) ||
    ((ex.day>=1 && ex.day<=12) && (ex.month==4 || ex.month==6))) {
        printf("%d is valid  date.\n", ex.day);
        return 1;
    }
    printf("%d is invalid date.\n", ex.day);
    return 0;
}
  • Related