C++ Primer For Java Programmers


The Main Function

<< | Table of Contents | Variables And Data Types >>
C++ is similar to Python in that it includes both standalone functions and methods within classes. In Java, every subroutine is a method (or static method) of some class.

All programs must have a starting point for execution. In both Java and C++, the first statement executed is the first statement within the program's main() function. The difference is that in C++, the main routine is a standalone function while in Java it is a static method of a class. The following illustrates the basic Hello World program in C++

(:source lang=cpp:)
// Hello world program in C++.
#include <cstdio>

int main( int argc, char *argv[] )
{
  printf( "Hello World!\n" );
}

and the equivalent in Java.

(:source lang=java:)
// Hello world program in Java.
class MyProgram {
  public static void main( String [] args ) 
  {
    system.out.println( "Hello World!" );
  }
}

The two arguments to the main C++ routine are used to access the command-line arguments. If your program has no need for command-line arguments, you can use the following version of the main routine instead.

(:source lang=cpp:)
// Alternate form of the main() C++ routine.
#include <cstdio>

int main()
{
  printf( "Hello World!\n" );
}


<< | Table of Contents | Variables And Data Types >>

Print - Changes - Search
Last modified: April 27, 2007, at 01:54 PM.