C++ Syntax and Program Structure



Explanation of C++ Basic Syntax

Every C++ program has an anatomy. Unlike human anatomy, the parts of C++ programs are not always in the same place. Nevertheless, the parts are there and your first step in learning C++ is to learn what they are.

The minimal C++ program is:


    int main() { }  // the minimal C++ program

This defines a function called main, which takes no arguments and does nothing. Curly braces, { }, express grouping in C++. Here, they indicate the start and end of the function body.

The double slash, //, begins a comment that extends to the end of the line. A comment is for the human reader; the compiler ignores comments.

Every C++ program must have exactly one global function named main(). The program starts by executing that function. The int value returned by main(), if any, is the program’s return value to "the system" If no value is returned, the system will receive a value indicating successful completion. A non zero value from main() indicates failure.

Typically, a program produces some output. Here is a program that writes Hello, World!:


    #include <iostream>
    int main(){
    std::cout << "Hello, World!\n";
    }                        

The line #include <iostream>instructs the compiler to include the declarations of the standard stream I/O facilities as found in iostream. Without these declarations, the expression would make no sense:


    std::cout << "Hello, World!\n"

The operator << ("put to") writes its second argument onto its first. In this case, the string literal "Hello, World!\n" is written onto the standard output stream std::cout.

A string literal is a sequence of characters surrounded by double quotes. In a string literal, the backslash character \ followed by another character denotes a single "special character" In this case, \n is the newline character, so that the characters written are Hello, World! followed by a newline.

Special Characters

The following table contains c++ special characters:

Character Name Description
// Double slash Marks the beginning of a comment.
# Pound sign Marks the beginning of a preprocessor directive.
< > Opening and closing brackets Encloses a filename when used with the #include directive.
( ) Opening and closing parentheses Used in naming a function, as in int main().
{ } Opening and closing braces Encloses a group of statements, such as the contents of a function.
" " Opening and closing quotation marks Encloses a string of characters, such as a message that is to be printed on the screen.
; Semicolon Marks the end of a complete programming statement.

Ads Right