Int main() problem

I'm a true beginner to c++. I can't find an explanation for what
int main(int nNumberofArgs, char* pszArgs[]) does? My Dummies book from which it comes, never explains it. Would appreciate a detailed simple explanation of why the things are in the parentheses.
This form of main() permits outside programs (most notably a terminal emulator) to call your program with string arguments.

If you type into a UNIX shell (any kind should work as long as it's not particularly exotic):
/path/to/my/program argumenta argumentb argumentc

Your int will contain 4 (your program's name and/or path is included), and your C-string array in each space will contain (individual arguments are separated by newlines here):
/path/to/my/program
argumenta
argumentb
argumentc

(The arguments in the shell are typically space separated)

The above input might also work with Windows's shell, but I wouldn't know.

This also permits calling a program with arguments via system() (using the same input) or some other program-calling function (see your OS's API documentation for a proper replacement for system() if you need it, DO NOT USE SYSTEM()).

Does this help?

-Albatross
Last edited on
Thanks. I appreciate your help, but need to what does int nNumberofArgd do, for example. When do I need to use this form, if ever. What if I leave out everything inside the parenthese, and just have the line a main()?
If you have just main(), outside programs will have... erm... some difficulty calling main() with arguments. The program will still compile though, and it will still run perfectly well as long as you don't rely on those arguments being defined.

The integer contains the number of arguments + 1 your program has received. In short, it tells you how big pszArgs[] is.

If you want other programs to be able to call your program using exec(), system(), or some other function that calls this program using string arguments, then that's one way you can do it: rely on this system of passing arguments to your program.

-Albatross



Last edited on
Simple example and explanation
http://www.cplusplus.com/forum/beginner/5404/#msg23839

More information for Windows users (with the same example)
http://www.cplusplus.com/forum/windows/6264/

Hope this helps.
Thanks to you guys. You've helped me.
Topic archived. No new replies allowed.