Let's examine the code for Hello World!
in detail.
Here is the code again.
|
1
#include <iostream.h>
2 int main()
3 {
4 cout << "Hello World!\n";
5 return 0;
6 } |
You should note I have added line numbers.
Line 1 - #include
<iostream.h>
The #include
directive is an instruction to the preprocessor to include the file iostream.h
in the Hello World! program. This file is necessary so that
the function cout on line 4
can be used. You can find out more about directives here.
Line 2 - int
main()
The program actually start with the
function called main(). Every
C++ program must start with this function. When your program
first starts, main() is called
automatically and the code inside it is executed.
Also, after all the code inside any
function has finished executing, the function can return a value. In
fact, every function is expected to declare what type of value it is
going to return In this case, the main()
function is declared with the word int
before it. This specifies that main()
will return an integer value.
This will be discussed further later
in the course.
Line 3 - {
All functions and sub routines in
C++ keep code enclosed between a pair of curly braces {}.
The end curly brace for the function main()
is on line 6. In effect, the braces define where the function starts
and ends. If you forget to type in a curly brace or type it in the wrong
place, you will get a compiler error.
Line 4 -
cout << "Hello World!\n";
This is the part of the program that
writes the words Hello World! to the command console.
cout
is the function that writes output to a screen
<<
is the output redirection operator. Whatever follows the
output redirection operator is written to the screen. If you want a
string of characters written, they must be enclosed in double quotes
(").
"Hello
World!\n" is the set of characters you want written
to the screen. The \n part
tells cout to put a new line after the words Hello World!
;
most lines of code in C++ end with a semi-colon.
Line 5 -
return 0;
As mentioned previously, the function
main is expected to return an integer value. Quite often, by convention
a programmer will return a 1 to indicate any errors,
and a 0 to indicate all is well.