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! 🎯
exit() FunctionThe 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. 💡
The syntax for the exit() function is simple:
#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.
Let's see an example of using the exit() function in a simple C program:
#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). 📝
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! 🚀