C++ Syntax | Learn C++ Programming Language

In programming, the term “syntax” signifies the set of predefined rules, processes, and protocols that everyone should follow, if they want an error-free code. Just like every other programming language, even C++ has its own distinctive syntax. 

In this article from TechVidvan, you’ll get a clear idea of the syntax of a C++ program. Let’s start!!!

C++ Program 

When we look at the C++ program, we can define it as a collection of interactive objects by invoking each other’s methods. Now let’s take a brief look at what class, object, methods, and instance variables mean:

  • Class: It is basically a template or a blueprint that describes the function/state of an object. 
  • Object: Object depicts states and behaviors of the data. A plant has its type, color, and characteristics. One should note that an object is just an instance of a class.
  • Methods: Behaviors are termed as methods in C++. Methods are the most important part of C++ as it helps to perform all tasks such as writing concepts, data processing, and all other actions. There can be many methods in a single class.
  • Instance Variables: The state of an object is usually determined by the values ​​given by the variables of the model as each item has its own unique set of instance variables.

C ++ Identifiers

In C++ every user-defined data including variable, function, class, and objects are named unique. The identifier is nothing but a term for such names. Identifiers can start with any letter of the English lexicon, irrespective of its case.

It can even begin with an underscore (_). It can also contain digits, but special symbols like @, $, and % are not allowed within C++ identifiers.

Since C++ is a case-sensitive language, TechVidvan and techvidvan are two different identifiers in C ++.

First C++ Program

Displaying “Hello World” is usually the first step to learn about the syntax of a programming language.

#include<iostream>
using namespace std;

int main()
{
/* This is the hello world program */
    cout <<"Hello World, welcome to TechVidvan! " << endl; //print statement
    return 0;
}

Output

Hello World, welcome to TechVidvan!

Components of C++ Program

From the above program, it is quite evident that there are many components in a C++ program. Here, at TechVidvan we will discuss every component to clear our understanding. 

1. Header files

Normally, the header file instructs the C ++ compiler to include all the functions associated with that title file. We have used just one header file, #include <iostream>, ‘iostream’ represents the input-output stream.

The <iostream> header file allows you to use input and output functionality. Hence, helped us to display the message “Hello World!” on the screen.

2. Namespace

A namespace is a descriptive region that provides scope to the identifiers (names of types, functions, variables, etc.) within them. We use namespaces to organize code into sensible groups and prevent possible word conflicts, especially when your codebase includes more than one library.

In the above program, we used using namespace std; which asks the compiler to use the std namespace. There’s another way of using namespace, by the use of the scope resolution operator “::” (we will learn about it in the future articles)

This is how we will use it:

std::cout<<"Hello world, welcome to TechVidvan!";

We write this line in every C++ program. Hence, whenever we write cout, the compiler knows that we mean std::cout.

3. Comments

To give details and explanations about the code or blocks of code, we need to use comments. Sometimes the code becomes a little tedious for the user to understand and we may need to explain our code, for that C++ supports comments. 

a. Single-line comments (//)

Single-line comment is prefixed with two front slashes “//” and it ends when the user jumps to another line. 

//print statement

This single-line comment makes the user/reader understand that this line is a print statement. Similarly, we can use them to explain what we as a writer mean by that particular line. 

b.  Multi-line comments (/* This is the hello world program */)

Multi-line comments begin with “/*” and end where “*/” is detected. 

Sometimes, we need to add comments of more than one line, for that C++ supports another type of comment. As writing it on one continued line makes it unreadable, we use multi-line comments or block comments when the explanation isn’t short.

It must be noted that comments are not code snippets, they are not a part of the code. Hence, if there is an error in the comments the compiler won’t detect them as it completely ignores them. It is always a good practice to use comments, it helps the user to understand the code better.

4. The main method

The program must contain a main() method and the program execution will fail if there’s no main() function. int main() is the main function where program execution begins and the return type is int. But, we are not done yet, without return 0; the main() function won’t terminate and the execution will fail.

5. Print statement

In C, we use printf() function along with format specifiers. Whereas in C++ we need not use format specifiers. We just need to use the cout function along with ‘<<’, the output operator. 

cout <<“Hello World, welcome to TechVidvan”<<endl;

As discussed earlier, we don’t have to mention the namespace during print statements if we have added using namespace std; at the start. 

In order to ask the compiler to move to the new line, we can use endl.

We can even use the escape sequence “\n” for the same purpose.

6. Tokens

A token is the smallest part of the program, which holds some meaning for the compiler. There are 5 types of token, they are:

  • Keywords
  • Identifiers
  • Constants
  • Strings
  • Special Symbols
  • Operators

Blocks and Semicolons in C++

In C++, a block is a group of logical statements wrapped in a pair of curly braces. Blocks are mainly used to connect logical statements with the same purpose.

For example:

{
a=1;
b=4;
sum=a+b;
cout<<sum; //to print the sum of a & b
}

In C++, a semicolon terminates the sentence. This means every C++ sentence must be ended with a semicolon. The compiler knows that it is the end of a sentence when there’s a semicolon, the end of the line is not recognized as a terminator. 

For example, 

int a,b; 
a=4,b=5;
cout<<a<<b;

Is the same as :

int a,b; a=4,b=5; cout<<a<<b;

Whitespaces in C++

Whitespaces are nothing but blank spaces which separate one part of the line of code from the other. They are required to denote tab spaces, blank spaces, end of line characters, and comments. 

For example: 

String TechVidvan;

If there was no whitespace after String, the compiler would have failed to distinguish between datatype and variable name.

Rules while writing a C++ program

1. C++ is a case-sensitive language i.e. it treats upper-case and lower-case alphabets differently. 

2. Most of the keywords are in lower-case and they must be kept in mind before naming the tokens. 

3. Every line of code must be terminated by a semicolon, or else it will throw an error.

4. Whitespace must be properly allocated between keywords and variables in C++.

Keywords in C++

As we discussed earlier about the identifiers, we should now know about Keywords and their importance. In C++, there are certain words whose meaning is already explained to the compiler.

Such “reserved words” are termed as Keywords. Since they have a predefined meaning, we must not use them as identifiers.

C++ language has 75 keywords that are not to be used as identifiers in a C++ program:

asm else new this
auto enum operator throw
bool explicit private true
break export protected try
case extern public typedef
catch false register typeid
char float reinterpret_cast typename
class for return union
const friend short unsigned
const_cast goto signed using
continue if sizeof virtual
default inline static void
delete int static_cast volatile
do long struct wchar_t
double mutable switch while
dynamic_cast namespace template

Escape Sequences in C++

Control characters are non-printing characters used to control the printing behavior of the display stream objects. They are also known as escape sequences and are not displayed on the output screen.

Escape sequences can be inserted anywhere in the string and they begin with a backslash followed by the character which controls the display. 

Some of the control characters along with their meanings are :

  • \a – Bell
  • \n – New line
  • \r – Carriage return
  • \b – Backspace
  • \f – Formfeed
  • \t – Horizontal tab
  • \ – Quotation mark
  • \v – Vertical tab
  • \’ – Apostrophe
  • \\ – Backslash
  • \? – Question mark
  • \0 – Null

Let’s learn the concept of escape sequence by implementing them:

For example, 

#include<iostream>
using namespace std;

int main()
{
    cout <<"Welcome to TechVidvan!Hope you are enjoying learning ";
    return 0;
}

Output

Welcome to TechVidvan!Hope you are enjoying learning

For some reason, if you want to break the print statement and display it in separate lines, you just need to insert the escape sequence for the new line “\n” in the middle of the string.

#include<iostream>
using namespace std;

int main()
{
    cout <<"Welcome to TechVidvan! \nHope you are enjoying learning ";
    return 0;
}

Output

Welcome to TechVidvan!Hope you are enjoying learning

Trigraphs in C++

A few letters have another representation, called trigraph sequence. Trigraph represents a single letter even though it is a three-letter sequence. It is usually prefixed with two question marks ‘??’.  

Trigraphs are extended wherever they appear, including alphabetical and character texts, in comments, and in the preprocessor.

The following are the most commonly used trigraph sequences along with their replacements:-

  • ??= →  #
  • ??/ →  \
  • ??’ →  ^
  • ??( →  [
  • ??) →  ]
  • ??! →  |
  • ??< →  {
  • ??> →  }
  • ??- →  ~

Conclusion

In this tutorial, we got to know about the components of the “Hello World” C++ program. It helped us to learn about the main() method, comments, tokens, etc.

We then went through the concepts of blocks, white spaces, keywords, and the escape sequence. Along with all this, we even got to know the basic rules of writing a C++ program which will help us in the future.