Saturday, June 19, 2010

A simple C++ program

Let me explain some features of a C++ program by using the following example.

#include <iostream>// include header file

using namespace std;

int main()
{
   cout << "This is my first C++ program.\n"; // a C++ statement
   return 0;
}
// End of example

A C++ program is a collection of functions like a C program. In the above example, there is only one function, main(). Program execution begins at main(), and every C++ program must have a main().

Comments
C++ uses a double slash (//) as a comment symbol. Comments start with a double slash and terminate at the end of the line. A comment can start anywhere in the line, and whatever follows till the end of hte line is treated as a comment. There is no closing symbol for a C++ comment.

Multiline comments can be written as follows:

// This is an
// example to illustrate
// C++ program features

You can also use the C comment symbols /*, */ for multiline comments. For example,

/* This is an
    example to illustrate
    C++ program features
*/

Output Operator

The statement 

   cout << "This is my first C++ program.\n";

is the only statement in the above example. This statement displays the string within the quotation marks on the screen. The identifier cout (pronounced as 'C out') is a predefined object that represents the standard output stream in C++.


The operator << is called the insertion operator. It inserts the contents of the variable on its right to the object on its left.

The iostream file

The directive

   #include <iostream>

causes the preprocessor to add the contents of the iostream file to the program. This directive contains declarations for the identifier cout and the operator <<. The header file iostream should be included at hte beginnning of all programs that use input/output statements.

Namespace

Namespace is a new concept introduced by the ANSI C++ standards committee. This defines a scope for the identifiers used in the program. In the statement

   using namespace std;

std is the namespace where ANSI C++ standard class libraries are defined. This will bring all the identifiers defined in std to the current global scope. using and namespace are the new keywords introduced in C++.

Return type of main()

In C++, main() returns an integer type value to the operating system. Therefore, every main() in C++ should end with a retunr (0) statement; otherwise, a warning or an error might occur. Since main() returns an integer type, return type of main() is explicitly specified as int.