The main( ) Function

The main( ) Function

In a C/C++ program, execution begins at main( ). (Windows programs call WinMain( ), but this is a special case.) You must not have more than one function called main( ). When main( ) terminates, the program is over and control passes back to the operating system.

The main( ) function is not prototyped. Thus, different forms of main( ) may be used. For both C and C++, the following versions of main( ) are valid:

int main() int main(int argc, char *argv[])

As the second form shows, at least two parameters are supported by main( ). They are argc and argv. (Some compilers will allow additional parameters.) These two variables will hold the number of command-line arguments and a pointer to them, respectively. argc is an integer, and its value will always be at least 1 because the program name is the first argument as far as C/C++ is concerned. argv must be declared as an array of character pointers. Each pointer points to a command-line argument. Their usage is shown below in a short program that will print your name on the screen:

#include <iostream> using namespace std; int main(int argc, char *argv[]) {   if(argc<2)     cout << "Enter your name.\n";   else     cout << "hello " << argv[1];   return 0; }




C(s)C++ Programmer's Reference
C Programming on the IBM PC (C Programmers Reference Guide Series)
ISBN: 0673462897
EAN: 2147483647
Year: 2002
Pages: 539

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net