Descriptions of main()

Hi everyone, I just joined this forum -

I am brand new to C++ and had some questions. I had previously been working a little bit with functions in Python and never had to deal with a main() function. In C++ it seems every program has a main() function, if I understand correctly.

What I am wondering is if someone could explain the main() function and its purpose. Does the main function contain all the processes of the program? In using the functions and writing the actions the program is to perform, are all those actions supposed to be housed within the main() function? What types of things does main() return?

Thanks so much. Sorry my question is so basic, I just want to be sure I have the right understanding before I go on with reading the book.
Hi Radergan and welcome!

The main function is the main entry point into a C or C++ program. This can be changed, but no one usually does. The main function usually doesn't contain very much at all unless the program is simple. I usually use main to gather any command line arguments and depending on what my program is doing, I'll call functions in other modules. These of course can be modules I write, and/or modules in libraries I might choose to link in to my program.

Main usually returns an integer which gets returned to the operating system.

Hope this helps!
Just a few edits to kooths otherwise great explaination:

- Specifically Win32 applications should change the entry point from main(...). This is because there are a few more arguments passed to the entry point from the OS other then an array of char pointers and if you're writting for Windows this is a habit you should get into early.

- Main(...) should ALWAYS return an integer to the OS. This is part of the current and future standard for C++.
should ALWAYS return an integer to the OS

As far as I am aware, the OS doesn't often care to use this value, but of course that doesn't mean you shouldn't return one.

I usually use 0 for success and 1 for failure.
The OS doesn't care about the value, its only job is to pass it to the application that spawned the process.
It's up to the actual programs to do something with that value.
Thanks Comptergeek01! I forgot about Windoze! ;)

I said Main usually returns an integer in that a lot of programmers do not call return -- but you're right: We should always return a meaningful value. On UNIX and the like zero means success and anything else, not so much ...

And let me rephrase about the return code to the OS: The OS will return whatever is in its AX (or similar) register to the calling process.
Topic archived. No new replies allowed.