0

I understand that in functions other than main function when they return a value , that value can be used for other thing (such as calculation). And in "void" function there is no need to type "return".

But why there is always a need to type "return" in main function ? (Such as "return 0", "return 1", "return -1"....) When the values is not use for anything

Thinh
  • 230
  • 2
  • 12
  • 2
    The return value from main is the program's exit code – Claudiu Oct 15 '15 at 14:13
  • 1
    The value **is** used. Bashscripts for example. – cadaniluk Oct 15 '15 at 14:16
  • It is to indicate success or failure but it is **not** a necessity for `main` to have it . It is not a compulsory thing . – ameyCU Oct 15 '15 at 14:19
  • Since c99 is included return already (so no need to explicit type **return 0;**, this means it will automatically added. And for your question, it is because every function which returns int should have a return. – Michi Oct 15 '15 at 14:19
  • The return value of main is available to whoever started your program, and can be used to e.g. communicate error or success (so you can use that exit status in e.g. a shell, a .bat script, or another program that started your program). i.e. it is used. See all the answers or links in e.g. http://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c – nos Oct 15 '15 at 14:19
  • I'm not so sure this is a duplicate, since the question asks _why return_ not _what to return_. – Lundin Oct 15 '15 at 14:26

2 Answers2

1

Because the C standard says so. That being said, the C standard is not necessarily rational, since the language is very old and with many flaws.

Also it depends on which system you are programming for. In case your program is running on an OS, it must return int, period. There's not necessarily any rationale for it: the OS might decide to use your return code or completely ignore it

On bare metal systems, you usually don't have to return anything.

See this for a complete list of all different allowed combinations of main().

Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396
0

These values are used by the operating system to check whether the program exited normally (returned zero) or there was an error while executing it (non-zero return code).

ForceBru
  • 43,482
  • 10
  • 63
  • 98