How to end a program with an if statement?

20,266

Solution 1

The cheap answer is to call the exit() function.

However, exit() does not return -- the program exits immediately. So your validate() function would not return to its caller. This is a problem if there are any cleanup actions your program needs to do, such as saving state (score, whatever) to a file. The better way is to return some value from validate() that indicates to the caller that the program should end. You could do this by returning an int and moving the slot return value to a function argument which the function body can set. The caller can then do any cleanup it needs to do and return control to its caller, and so forth.

Solution 2

if (credits < 2)
{
    printf ("your credits are too low to play!");
    exit(EXIT_SUCCESS);    
}
Share:
20,266
user3311792
Author by

user3311792

Updated on July 09, 2022

Comments

  • user3311792
    user3311792 almost 2 years

    So this is a function from a slot machine project I'm working on. and I'm wondering is there a way to work it so that after the if statement claiming "your credits are too low to play" the program ends. Also can I make it so the program asks for the bet again if bet>credits or bet<2 any answers appreciated.

    slot validate( slot s)
    {
        printf ("Your available credit is %f\n", credits);
        if (credits >= 2)
        {
            printf ("How many credits would you like to bet?\n");
            scanf("%f", &s.bet);
            if (s.bet> credits)
            {
                printf("you do not have enough credits for that bet\n");
                printf("your available credits are %f", credits);
            }
    
            if (s.bet < 2)
            {
                printf("Error! You must bet at least to credits to play!");
            }
    
            if (credits < 2)
            {
                printf ("your credits are too low to play!");
            }
        }
    
        return s;
    }