by Dinesh Thakur Category: Function and Pointer

We have been writing "return 0;" as the last statement of every main function we have developed so far. But since main is the first function to start, no function calls main. So, the question that arises is - "Where does the return value of main go?" The value is returned and stored by the operating system and can be used to guide further actions by the operating system using shell scripts/batch files.

Just as an example, we will discuss the handling of main's return value in the MS-Windows environment. When a program is executed in Windows, any value returned from the main function is stored in an environment variable called ERRORLEVEL. By inspecting the ERRORLEVEL variable, batch files can therefore determine the outcome of execution. By tradition, a return value of zero indicates successful execution. Below is a very simple program HELLORETURN. C that returns a zero from the main function if a positive value is input, else it returns 1.

/*Program showing use of main's return value.*/

#include <stdio.h>
int main()
    int k;
       return 0;
                return 1;

Next, we write a batch file named TEST.BAT with the following commands of the Windows environment. Do not worry if you do not understand the entire file which is written in the scripting language of MS-Windows. Notice that our program Hello Return is executed in the third line of the batch file.

rem test.bat

@echo off


@if "%ERRORLEVEL%" == "O" goto good


    echo Execution Failed

    echo return value = %ERRORLEVEL%

    goto end


    echo Execution succeeded

    echo return value = %ERRORLEVEL%

    goto end


Next, we execute this batch file. After completing execution of the Hello return program, the return value of main is stored in the ERRORLEVEL system variable. By testing this value, different actions can be taken by the batch file. Two different executions of the batch file are shown below. The user gives an input of 3 in the first case and an input of -3 in the second case. See the different actions taken by the batch file.

c:\cclass>rem test.bat
Execution succeeded
return value = 0

c:\cclass>rem test.bat
Execution Failed
return value = 1

By integrating the use of ERRORLEVEL variable into our shell scripts/batch files, we can create very efficient and effective shell scripts/batch files.

Popular Article