#10 – The Return Value from Main() Sets ERRORLEVEL Variable in Windows

If your Main() function returns an integer value, you can check that value in the calling program or script using the ERRORLEVEL environment variable.  By convention, a return value of 0 indicates success and any other value indicates an error.  Below is a sample .bat file that calls a program called MyProgram and then checks the return value.

@echo off

MyProgram

IF "%ERRORLEVEL%" == "0" goto OK

:NotGood
    echo Bad news.  Program returned %ERRORLEVEL%
    goto End

:OK
    echo Everything A-OK

:End

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

9 Responses to #10 – The Return Value from Main() Sets ERRORLEVEL Variable in Windows

  1. S.K.C says:

    i didnt get it…how it works… ???

    • zzhi says:

      @echo on

      2000CSharp

      IF “%ERRORLEVEL%” == “0” goto OK

      :NotGood
      echo Bad news. Program returned %ERRORLEVEL% >>log.txt
      goto End

      :OK
      echo Everything A-OK>>log.txt

      :End

  2. Sean says:

    The ERRORLEVEL environment variable is automatically set by Windows to contain the return value of your program. In the example above, if your program returned a value of -1, the script would echo “Bad news. Program returned -1”. If your program returned 0, the script would echo “Everything A-OK”.

  3. msuworld says:

    didn’t understand the batch script, as it only runs the program and nothing else happens even if i put errorlevel 1 instead of 0

    • Sean says:

      If the %ERRORLEVEL% variable in the .bat file will contain the value that you program returned. So if you exit your program with a statement like “return 5”, then the %ERRORLEVEL% variable will contain the value of 5 after invoking the program.

  4. Parveen Arora says:

    Sorry but i still don’t understand how to implement this practically. Plz explain.

Leave a comment