-3

I am just starting out in C++ and we are learning about typical statements in code. One that we typically use is int main() at the start of the actual program portion. I understand we can also use void main(). My question is, why do we use int? I thought this was for defining variable types. Are we actually declaring that the whole code is a variable?

  • 3
    You cannot actually use `void main()`. It's not allowed by the language. Your compiler may allow it, but it isn't portable. – François Andrieux Jun 12 '18 at 19:05
  • 2
    `int main()` defines a function, not a variable. The leading type is the type of value the function returns. – François Andrieux Jun 12 '18 at 19:06
  • In a way, yes, the whole program is a variable, an `int` which the program returns on exit. – quamrana Jun 12 '18 at 19:06
  • https://stackoverflow.com/questions/449851/why-do-we-need-to-use-int-main-and-not-void-main-in-c More info here https://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c – Vivek Jun 12 '18 at 19:08
  • If it is defined `int` then it expects to return a value. This is the "result". If it is `void` it does not expect to return a value. – Andrew Truckle Jun 12 '18 at 19:15

1 Answers1

1

The main function (which is your entry point to the program) is defined by the C++ standard to always return int. void main is not valid according to the standard (even if your compiler accepts it).

The purpose of the int return value is to return a value to the operating system, telling it whether your program completed successfully or not. There are two well-defined macros available for returning such a value that you can depend on having a sane meaning - they are EXIT_SUCCESS and EXIT_FAILURE. You can return other values than those, but only those are guaranteed to have a sane semantic meaning - any other value is going to be platform/OS dependent (and while EXIT_SUCCESS is usually zero, you can't depend on that - on VMS (for example) that is not true, so you really should use the macros in portable code - and regardless, return EXIT_SUCCESS; communicates meaning much clearer than return 0;).

main is special compared to all other functions though, in that if no value is explicitly returned it implicitly returns EXIT_SUCCESS - I personally don't like relying on that though; I prefer explicitly returning what I intend to return.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70