C exit codes
Created By: chatGPT
Exit codes in C are used to indicate the completion status of a program. They are typically returned by the
main
function and can be used to signify whether the program executed successfully or encountered an error. By convention, an exit code of 0
indicates success, while any non-zero value represents an error. Here's a simple example:#include <stdio.h>
int main() {
// Successful execution
return 0;
}
int main() {
// Error scenario
return 1;
}
You can also use the
exit()
function from the <stdlib.h>
library for terminating the program with a specified exit status. This allows you to exit from anywhere within your program rather than just at the main
function's return statement in case of complex programs:#include <stdio.h>
#include <stdlib.h>
void check_condition(int condition) {
if (condition) {
printf("Success\n");
exit(0);
} else {
printf("Error occurred\n");
exit(1);
}
}
int main() {
check_condition(1);
check_condition(0);
}
When calling a program from the terminal or another script, you can check the exit code by using
$?
in a shell environment, which contains the exit code of the last executed command. Here's a brief example of how this works:gcc program.c -o program
./program
echo $? // This will print the exit code
Using meaningful exit codes is essential for debugging and understanding the flow of a program. You can define custom exit codes by returning distinct integers for various error conditions. For example:
#include <stdio.h>
#define SUCCESS 0
#define ERROR_FILE_NOT_FOUND 1
#define ERROR_PERMISSION_DENIED 2
int main() {
printf("File not found!\n");
return ERROR_FILE_NOT_FOUND;
}