Before diving too deeply into differences, let's start by reviewing what is the same, or at least nearly the same.
Note that there are a few "forward references" below to material you will read in the next few sections of this web site. It is not important while reading this material to fully understand what is described in those forward references – just a basic intuitive idea will suffice for now. You will see and understand that material very shortly.
//
style as well as the potentially multiline /* … */
.
|
if
, for
, while
, switch
, etc.) are
essentially identical. Minor differences occasionally appear for newer variations such as
Java's "for each" construct that will be mentioned in the section on Arrays.
main
: Execution of a C++ or Java program is
the same in that the runtime system will look for an appropriate entry point named
main
and initiate execution of your program by causing control to start
at the first statement of the identified main function. The primary differences
include:
main
method, and the runtime system decides which to run based on how you launch the program.
In C++, there must be exactly one entry point called main
, and it must be a
function declared at global scope outside
all classes. (See Identifiers at global scope in the navigation panel on
the left.)main
methods must be:
public static void main(String[ ] args)
whereas the prototype for the one C++ main
function can be either:
int main( )
int main(int argc, char* argv[ ])
If the latter, argv
plays the same role as does args
in
the Java case.
Because the C++ runtime system cannot determine the length of an array (as will be
described in the Arrays section), argc
contains the length of the argv
array on entry to main
.
You will learn about the differences between Java's "String[ ] args"
and C++'s "char* argv[ ]" in the Character strings section.
main
method must return
an integer value. Typically you just "return 0;
", but you can return
other values (typically error codes) which might be retrievable for use by the host
operating system.As a comparative example (output to the screen using std::cout will be discussed in the Keyboard/Screen I/O section):
Java | C++ |
public class Example { public static void main(String[] args) { for (int i=0 ; i<args.length ; i++) System.out.println(args[i]); } } |
#include <iostream> int main(int argc, char* argv[]) { for (int i=1 ; i<argc ; i++) std::cout << argv[i] << '\n'; return 0; } |
If I execute the Java program from a linux command line as:
I will see the same output as I would if I executed the C++ program from a linux command line as:
This common output would be:
chris book pat |
Notes: