Use of exit() function

2020-01-27 12:48发布

I want to know how and when can I use the exit() function like the program in my book:

#include<stdio.h>

void main()
{
    int goals;
    printf("enter number of goals scored");
    scanf("%d",&goals);

    if(goals<=5)
        goto sos;
    else
    {
        printf("hehe");
        exit( );
    }
    sos:
    printf("to err is human");
}

When I run it, it shows ERROR: call to undefined function exit().

Also, I want to know how I can create an option to close the window in which the program runs? For example, I made a menu-driven program which had several options and one of them was "exit the menu". How can I make this exit the program (i.e. close the window)?

标签: c
13条回答
叼着烟拽天下
2楼-- · 2020-01-27 12:55

exit(int code); is declared in stdlib.h so you need an

#include <stdlib.h>

Also:
- You have no parameter for the exit(), it requires an int so provide one.
- Burn this book, it uses goto which is (for everyone but linux kernel hackers) bad, very, very, VERY bad.

Edit:
Oh, and

void main()

is bad, too, it's:

int main(int argc, char *argv[])
查看更多
成全新的幸福
3楼-- · 2020-01-27 12:56

The following example shows the usage of the exit() function.

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

int main(void) {
    printf("Start of the program....\n");
    printf("Exiting the program....\n");
    exit(0);
    printf("End of the program....\n");
    return 0;
}

Output

Start of the program....
Exiting the program....

查看更多
神经病院院长
4楼-- · 2020-01-27 13:01

The exit() function is a type of function with a return type without an argument. It's defined by the stdlib header file.

You need to use ( exit(0) or exit(EXIT_SUCCESS)) or (exit(non-zero) or exit(EXIT_FAILURE) ).

查看更多
做个烂人
5楼-- · 2020-01-27 13:07

The exit function is declared in the stdlib header, so you need to have

#include <stdlib.h>

at the top of your program to be able to use exit.

Note also that exit takes an integer argument, so you can't call it like exit(), you have to call as exit(0) or exit(42). 0 usually means your program completed successfully, and nonzero values are used as error codes.

There are also predefined macros EXIT_SUCCESS and EXIT_FAILURE, e.g. exit(EXIT_SUCCESS);

查看更多
女痞
6楼-- · 2020-01-27 13:08

Write header file #include<process.h> and replace exit(); with exit(0);. This will definitely work in Turbo C; for other compilers I don't know.

查看更多
迷人小祖宗
7楼-- · 2020-01-27 13:11

Try using exit(0); instead. The exit function expects an integer parameter. And don't forget to #include <stdlib.h>.

查看更多
登录 后发表回答