C exit() Function

beginner
10 min

C exit() Function

Welcome to our comprehensive guide on the exit() function in C programming! This function is a handy tool for terminating a program and returning a status code. Let's dive right in! 🎯

Understanding the exit() Function

The exit() function is used to terminate the current process and return a status code to the operating system. It's different from the return statement, which is used to exit a function but keeps the program running. 💡

Syntax

The syntax for the exit() function is simple:

c
#include <stdlib.h> void exit(int status);

The status parameter is an integer that represents the exit status of the program. This can be useful for indicating the success or failure of the program to the operating system or other programs.

Practical Application

Let's see an example of using the exit() function in a simple C program:

c
#include <stdio.h> #include <stdlib.h> int main() { int n; printf("Enter a number: "); scanf("%d", &n); if (n < 0) { printf("Invalid input. Exiting..."); exit(EXIT_FAILURE); // Return an error code } printf("The square of the entered number is: %d\n", n*n); return EXIT_SUCCESS; // Successful exit }

In this example, we check if the user input is negative. If it is, we print an error message and exit the program using the exit() function with an error code (EXIT_FAILURE). If the input is valid, we calculate the square of the number and exit the program with a success code (EXIT_SUCCESS). 📝

Quiz Time!

Quick Quiz
Question 1 of 1

Which function is used to terminate a C program and return a status code?

That's it for our introductory lesson on the exit() function in C programming! Stay tuned for more engaging and informative lessons here at CodeYourCraft. Happy coding! 🚀