1

As far as I understand if the main function returns 0 this indicates always successful program termination. Even if success is indicated by another int value.

If main returns a non-zero value it is implementation specific if this stands for unsuccessful program termination or another error code

If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If the value of status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.)

So only success is defined in the C standard (return 0) and not how a non-zero int value is interpreted, right? E.g. if in a certain system 1 stands for "success" return 0 would be deliver 1 as well? How is this done?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
knowledge
  • 941
  • 1
  • 11
  • 26
  • The standard defines what it does, and nothing more. How that achieved, that's outside the province of the standard. Though under Unixoids and Windows, it's an identity-mapping (mod 256). – Deduplicator Aug 25 '15 at 18:07
  • Closely related: http://stackoverflow.com/q/8867871/827263 (I'm not sure it's exactly a duplicate). – Keith Thompson Aug 25 '15 at 18:35
  • A language standard cannot easily define what the operating system should do with the returned value. Some systems don't care at all what is returned, and the C standard cannot do much about that. – Bo Persson Aug 25 '15 at 23:17

1 Answers1

2

The main function is the entry point to your code, it is not the entry point to the executable. The executable contains an operating-system defined entry point, that runs some startup code before calling main.

main is called from the startup code just like a normal function. The return value from main is received by the startup code, which can perform any translations necessary to conform to the requirements of the operating system.

The startup code is specific to each operating system. Operating systems have requirements concerning the operation and environment of executables. The C language has requirements concerning the environment that the C code runs in (specifically the arguments to main and the return value from main). It's the responsibility of the startup code to bridge the gaps between those two sets of requirements.

The startup code is delivered as an object file, commonly called "crt.o", short for "C runtime". That file is included in the executable by the linker. You can find the actual name of that file by examining the linker command line. The startup file is typically the first file on the linker command line.

user3386109
  • 34,287
  • 7
  • 49
  • 68