I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com
Index » Programming » Tutorials » C & C++ » Basic »

Declaring the main entry point to your code

will\′s Photo
31 Oct 07, 2:59PM
Declaring the main entry point to your code
The core of all C or C++ function is a unique function called 'main'. The main is the entry point into your program and takes as arguments values from the command prompt.

As an example, consider this simple 'Hello world' program. This is fundamentally about as simple as they get using the stdio library to provide a mechanism to output to your console window (some call it a DOS window).
#include <stdio.h>
 
int main()
{
  printf("Hello World\n");
  return 0;
}
Note the declaration of main, which say it returns an int (integer). Then at the end of the main function we return 0. With Microsoft compilers you can often declare you main function as void, allowing you to omit the 'return 0;' statement. However this feature is not supported across all compilers, so for the most general use, write as we did above.

Command Line Arguments

To retrieve input from the command line, your main function should look something like this:
#include <stdio.h>
 
int main(int argc, char *argv[])
{
  printf("Hello there, you have provide %d arguments, which are:\n" ,argc);
  for(int i=0;i<argc;i++) printf("\t%s\n",argv[i]);
  return 0;
}
Not the main function now accepts two parameters, the first say how many arguments there are, the second is an array of strings (char*) that contain each parameter you entered on the command line.
Currently you need to be logged in to leave a message.