I just started learning C++ and the "main" function is kind of confusing to me. I know you can define your own functions, ones that can return different answers such as bools, strings, vectors, integers, doubles, etc. The "int" in front of the main should suggest that the main() function should return an integer, but yet it doesn't. Is the main() function just the same thing as a void function? Do I have to use an "int" in front of the main() in order for it to be the main function or can I use one of the others? Am I able to write code that doesn't have this centralized "int main()"?
Asked
Active
Viewed 72 times
0
-
2`main` always returns an `int`. There is no such thing as `void main()`. – digito_evo Dec 26 '21 at 22:48
-
1https://en.cppreference.com/w/cpp/language/main_function – JohnFilleau Dec 26 '21 at 22:48
-
It is the programmer's responsibility to have `main()` return a defined status to the operating system. Most commonly, one returns `EXIT_SUCCESS` or `EXIT_FAILURE`. – njuffa Dec 26 '21 at 22:49
-
2*"The "int" in front of the main should suggest that the main() function should return an integer, but yet it doesn't."* -- It **does** return an `int`. The special thing about `main` is that it does not have to **explicitly** return a value; for this function only, the compiler will supply a value to return if the programmer does not. (Go ahead and try putting a line like `return 42;` in your `main` function.) – JaMiT Dec 26 '21 at 22:50
-
You’ve never seen someone write return 0 at the end of a main function? – user438383 Dec 26 '21 at 22:51
-
If all I have in the main function would be to print "hello", what does the main function return as an integer? No I have never seen someone write return 0 at the end of a main function, but what would the point of that return 0 be? – Iredra Dec 26 '21 at 22:51
-
1@Iredra the result of running the program to the command shell (or other process that invoked the program). It's an arbitrary value, usually returning 0 to mean ok and other values for errors / warnings. – Richard Critten Dec 26 '21 at 22:52
-
*"If all I have in the main function would be to print "hello", what does the main function return as an integer?"* From the linked reference page: *"if control reaches the end of `main` without encountering a `return` statement, the effect is that of executing `return 0;`"* – JaMiT Dec 26 '21 at 22:54