Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how do i have constant value without a global variable in C using functions

So, i have this code:

#include <stdio.h>



void menu_loop(int run) {
    if (run == 0) {
        printf("bad\n");
        menu();
    }
    else
        printf("good");
}
int check_menu(int menu1) {
    if (menu1 > 3 || menu1 < 0)
        return 0;
    else
      return 1;
}
int menu() {
    int choice;
    printf("----MENU----\n0 -> Exit\n1 -> Prime time\n2 -> Calander calculating\n3 -> Matrix printing\n");
    scanf_s("%d", &choice);
    int check2 = check_menu(choice);
    menu_loop(check2);
}


void main() {
    menu();
}

what i need to do is whenever check_menu returns a 0 then i need to have a certein variable that starts at 0 go up by 1.
everytime i try this i find that the value gets reinitialized to 0 since im initializing it inside the function.
thanks in advance!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Returning an error code from a function in case something bad has happened is a common practice in C as it doesn’t has a concept of throwing an exception as in more high level languages. I recommend you defining a macro to be more explicit and use a loop instead of recursion.

#include <stdio.h>

#define INVALID_CHOICE_ERR 1

int check_menu(int menu1)
{
    if (menu1 > 3 || menu1 < 0)
        return INVALID_CHOICE_ERR;
    else
        return 0;
}

int menu()
{
    int choice;
    do {
        printf("----MENU----\n0 -> Exit\n1 -> Prime time\n2 -> Calander calculating\n3 -> Matrix printing\n");
        scanf_s("%d", &choice);
    } while (check_menu(choice) == INVALID_CHOICE_ERR);
    // Now that a valid choice has been selected, you can use it
}

void main()
{
    menu();
}

Or you can get rid of the macro and function by simplifying the while loop

while (choice > 3 || choice < 0);

Also I recommend you reading about the disadvantages of scanf() Disadvantages of scanf

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading