C++ Syntax

C++ provide simple program structure, that is much easier to understand. A basic C++ program consist of the the following lines of code.

Syntax using Namespace

1. #include <iostream>
2. using namespace std;
3. int main() {
4.  cout << "Hello World";
5.  return 0;
6. }

Code Explanation

We will discuss this code snippet line by line.

Line No 1: This line is called preprocessor directive. This is usually the first line in entire C++ programs. This is used to include header files in program. These are also called library files.

Line No 2: This is namespace defination line. This line is used for using name of objects from included libraries. Here std stands for standard (refers to standard input and output). This line can also be skipped that we will also discuss later in this topic.

Line No 3: This is called main function. This is most important point in each and every C++ program. The entire logic of program is written in this function. Each C++ must have main function. int main ( ) has three parts as any oth ordinary function.

  • Return Type - int
  • Name - main
  • Parameters - ()
  • Starting of function - {

Line No 4: This line uses cout (pronunciate as C-OUT) object from iostream library. This is called insertion oprator. This operator is used to send data to standard output device called monitor. There is also complete syntax of using this insertion operator in C++ as:

  • cout - standard console output object
  • << - insertion operator
  • "Hello world" - format string enclosed in double quotes
  • ; - termination of C++ statement

Line No 5: This is called return of function. It is last line of any function. This may return different type of data depending on the function return type. In C++ programs return 0 is used to indicate successfull completion of main function.

Line No 6: This is closing delimiter of main function.

Syntax without using Namespace

1. #include <iostream>
2. int main() {
3.  std::cout << "Hello World";
4.  return 0;
5. }

The above code does not use namespace statement. When we omit using namespace statement than we have to add std:: with each object using from library.

So it is best practice to use namespace statement in every C++ program

Comments
Login to TRACK of Comments.