0
0
Cprogramming~5 mins

Using return codes

Choose your learning style9 modes available
Introduction

Return codes help a program tell if a task worked or if there was a problem. They are simple numbers that show success or failure.

When a function needs to say if it finished its job correctly.
When you want to check if a file opened successfully.
When you want to know if a calculation or operation gave a valid result.
When you want to stop a program early if something goes wrong.
When you want to communicate status between different parts of a program.
Syntax
C
int functionName() {
    // do some work
    return 0; // 0 means success
    // or return 1; // non-zero means error
}

By convention, 0 means success and any non-zero value means an error.

Return codes are integers that tell the caller what happened inside the function.

Examples
This function returns 0 if the file opens, 1 if it fails.
C
int openFile() {
    // try to open a file
    if (/* file opened */) {
        return 0; // success
    } else {
        return 1; // error
    }
}
This function returns 1 if division by zero happens, otherwise 0.
C
int divide(int a, int b, int *result) {
    if (b == 0) {
        return 1; // error: division by zero
    }
    *result = a / b;
    return 0; // success
}
Sample Program

This program checks if a number is positive using a return code. It prints a message based on the result.

C
#include <stdio.h>

int checkNumber(int num) {
    if (num > 0) {
        return 0; // success: positive number
    } else {
        return 1; // error: not positive
    }
}

int main() {
    int number = -5;
    int code = checkNumber(number);

    if (code == 0) {
        printf("Number %d is positive.\n", number);
    } else {
        printf("Number %d is not positive.\n", number);
    }

    return 0;
}
OutputSuccess
Important Notes

Always check return codes to handle errors properly.

Use meaningful return codes to explain different error types.

Return codes make your program more reliable and easier to debug.

Summary

Return codes are numbers that show if a function worked or failed.

0 usually means success, non-zero means error.

Check return codes to handle problems early and clearly.