How to exit c program?

by jayson.maggio , in category: C/C++ , 2 years ago

How to exit c program?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@jayson.maggio You can use exit() function to exit any c program, code as example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <cstdio>
#include <cstdlib>

int main(int argc, char *argv[]) {
    printf("Start");
    exit(0);
    printf("End");
    // Output: Start

    return 0;
}
by cyril.littel , 10 months ago

@jayson.maggio 

There are different ways to exit a C program:

  1. Return from the main() function: The main() function is the entry point of a C program. When it ends, the program terminates. You can exit from the program by returning a value from the main() function. The return statement is used to return a value to the system that called the main() function. A return value of 0 indicates a successful termination of the program.


Example:

1
2
3
4
5
int main()
{
   // program code
   return 0; // exit program
}


  1. The exit() function: The exit() function is used to terminate a C program. It takes an integer parameter that specifies the exit status of the program. The exit status is a value that indicates whether the program completed successfully or encountered an error. A value of 0 indicates a successful termination.


Example:

1
2
3
4
5
6
#include <stdlib.h>
int main()
{
   // program code
   exit(0); // terminate program
}


Note: You need to include the stdlib.h header file to use the exit() function.

  1. The abort() function: The abort() function is used to terminate a C program abnormally. It does not perform any cleanup operations and exits immediately. You should use this function only in extreme cases when your program encounters a fatal error.


Example:

1
2
3
4
5
6
#include <stdlib.h>
int main()
{
   // program code
   abort(); // terminate program abnormally
}


Note: You need to include the stdlib.h header file to use the abort() function.