Monday, September 29, 2008

Introduction to C++

Structure of a C++ Program

Structure of a C++ program is shown as a collection from one or more function.

Example:

#include

void main()

{

Statement1

Statement2

Statement3

}

File header declaration based on the statement we are used. Following a simple program in C++:

#include

void main()

{

clrscr();

cout<<”Hello World”;

getch();

}

We are going to look them one by one:

#include

Sentences that begin with a pound sign (#) are directives for the preprocessor. They are not executable code lines but indications for the compiler. In this case the sentence #include tells the compiler's preprocessor to include the iostream standard header file. This specific file includes the declarations of the basic standard input-output library in C++, and it is included because its functionality is used later in the program.

void main ()

This line corresponds to the beginning of the main function declaration. The main function is the point where all C++ programs begin their execution. It is independent of whether it is at the beginning, at the end or in the middle of the code - its content is always the first to be executed when a program starts. In addition, for that same reason, it is essential that all C++ programs have a main function.

main is followed by a pair of parenthesis () because it is a function. In C++ all functions are followed by a pair of parenthesis () that, optionally, can include arguments within them. The content of the main function immediately follows its formal declaration and it is enclosed between curly brackets ({}), as in our example.

cout << "Hello World";

This instruction does the most important thing in this program. cout is the standard output stream in C++ (usually the screen), and the full sentence inserts a sequence of characters (in this case "Hello World") into this output stream (the screen). cout is declared in the iostream.h header file, so in order to be able to use it that file must be included.

Notice that the sentence ends with a semicolon character (;). This character signifies the end of the instruction and must be included after every instruction in any C++ program (one of the most common errors of C++ programmers is indeed to forget to include a semicolon ; at the end of each instruction).

Comments

Comments are pieces of source code discarded from the code by the compiler. They do nothing. Their purpose is only to allow the programmer to insert notes or descriptions embedded within the source code.

C++ supports two ways to insert comments:

// line comment
/* block comment */



Source : Cplusplus.com

No comments: