C++ Primer for Java Programmers

 

The Main Function

Cpp PrimerVariables 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++

// Hello world program in C++.
#include <cstdio>

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

and the equivalent in 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.

// Alternate form of the main() C++ routine.
#include <cstdio>

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



Cpp PrimerVariables And Data Types
Print -- Recent Changes
Page last modified on April 27, 2007, at 01:54 PM