CodeBlanks Logo Icon CodeBlanks

Exit codes

  • C course
  • Intermediate
  • Lesson 92/116
  • 5 min

Learn program exit codes with exit.

exit and return codes

When a C program ends it returns an exit code to the shell. 0 means success; any non-zero value signals an error. Two ways exist: return from main or call exit from <stdlib.h>.

exit(1) ends the program at once; remaining code never runs. return 1 only leaves main. exit is handy for escaping a deep call stack. The constants EXIT_SUCCESS and EXIT_FAILURE improve readability over raw 0 and 1. The shell checks the last exit code with $?.

Conditional exit

Calling exit on error prevents the program from entering an inconsistent state. When the condition holds, exit inside an if block skips the remaining code.

Example: if (error) { printf("Problem\n"); exit(1); }. Here, if error is true the program prints a message and stops at once; lines after exit never run. This pattern is common for operations that can fail such as file opening or memory allocation. exit flushes and closes open files and calls functions registered with atexit, giving a clean shutdown.

Practice Write a conditional exit

Add #include <stdlib.h>. Declare int hata = 1;. Print printf("Başlıyor\n");. Inside an if (hata) block print printf("Sorun\n"); and call exit(1);. After the if, print printf("Bitti\n");.

Starter code

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

// Define hata as 1
// Print "Başlıyor"
// If hata, print "Sorun" and stop the program
// Print "Bitti"

int main(void) {
    return 0;
}

Sample solution

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

int main(void) {
    int hata = 1;
    printf("Başlıyor\n");
    if (hata) {
        printf("Sorun\n");
        exit(1);
    }
    printf("Bitti\n");
    return 0;
}

Expected output

Başlıyor
Sorun

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the exit codes

Term Meaning
0 Success
1 Error
exit(1) Stop now
return 0 Leave main

2 Complete the exit call

Question
if (status != 0) exit(____);
Answer
if (status != 0) exit(1);

Explanation: exit(1) signals the error to the shell.

3 What happens to code after exit(1)?

  • It keeps running
  • It never runs Correct answer
  • It enters an infinite loop
  • It triggers a compiler warning

Explanation: exit(1) ends the program at once; subsequent code never runs.

All lessons in Intermediate