Simple C++ Program with explanation and examples. Explain C++ Program
Simple C++ Program
// my first program in C++
#include <iostream>
void main ()
{
cout << "Hello World!";
}
// my first program in C++
This is a comment line. All lines beginning with two slash signs (//) are considered comments and do not have any effect on the behavior of the program. The programmer can use them to include short explanations or observations within the source code itself. In this case, the line is a brief description of what our program is.
C++ supports two ways to insert comments:
// line comment
/* block comment */
#include <iostream>
Lines beginning with a pound sign (#) are directives for the preprocessor. They are not regular code lines with expressions but indications for the compiler's preprocessor. In this case the directive #include <iostream> tells the preprocessor to include the iostream standard file. This specific file (iostream) includes the declarations of the basic standard input-output library in C++, and it is included because its functionality is going to be used later in the program.
void main ()
This line corresponds to the beginning of the definition of the main function. The main function is the point by where all C++ programs start their execution, independently of its location within the source code. It does not matter whether there are other functions with other names defined before or after it.This function's definition will always be the first ones to be executed in any C++ program. For that same reason, it is essential that all C++ programs have a main function.
cout << "Hello World";
This line is a C++ statement.This statement performs the only action that generates a visible effect in our first program.
cout represents the standard output stream in C++.The operator << is called the insertion or put to operator and the meaning of the entire statement is to insert a sequence of characters (in this case the Hello World sequence of characters) into the standard output stream (which usually is the screen).
We could have written:
int main () { cout << "Hello World"; return 0; }
Notice that the statement ends with a semicolon character (;). This character is used to mark the end of the statement and in fact it must be included at the end of all expression statements in all C++ programs.
Labels: C++