The Wayback Machine - https://web.archive.org/web/20240729013950/https://www.geeksforgeeks.org/cpp-basic-syntax/
Open In App

C++ Basic Syntax

Last Updated : 09 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

C++ is a general-purpose, object-oriented programming language. It was developed in 1979 by Bjarne Stroustrup at AT & T Bell Laboratory. It is a high-level programming language & advanced version of C programming language. As Compared to other programming languages like Java, and Python, it is the fastest programming language.

What is Syntax?

Syntax refers to the rules and regulations for writing statements in a programming language. They can also be viewed as the grammatical rules defining the structure of a programming language.

The C++ language also has its syntax for the functionalities it provides. Different statements have different syntax specifying their usage but C++ programs also have basic syntax rules that are followed throughout all the programs.

Basic Syntax of a C++ Program

We can learn about basic C++ Syntax using the following program.

Structure of C++ Program

 

The image above shows the basic C++ program that contains header files, main function, namespace declaration, etc. Let’s try to understand them one by one.

1. Header File

The header files contain the definition of the functions and macros we are using in our program. They are defined on the top of the C++ program.

In line #1, we used the #include  <iostream> statement to tell the compiler to include an iostream header file library which stores the definition of the cin and cout standard input/output streams that we have used for input and output. #include is a preprocessor directive using which we import header files.

Syntax:

#include <library_name>

To know more about header files, please refer to the article – Header Files in C/C++.

2. Namespace

A namespace in C++ is used to provide a scope or a region where we define identifiers. It is used to avoid name conflicts between two identifiers as only unique names can be used as identifiers.

In line #2, we have used the using namespace std statement for specifying that we will be the standard namespace where all the standard library functions are defined.

Syntax:

using namespace std;

To know more about namespaces in C++, please refer to the article – Namespaces in C++.

3. Main Function

Functions are basic building blocks of a C++ program that contains the instructions for performing some specific task. Apart from the instructions present in its body, a function definition also contains information about its return type and parameters. To know more about C++ functions, please refer to the article Functions in C++.

In line #3, we defined the main function as int main(). The main function is the most important part of any C++ program. The program execution always starts from the main function. All the other functions are called from the main function. In C++, the main function is required to return some value indicating the execution status.

Syntax:

int main() {

... code ....
return 0;
}

4. Blocks

Blocks are the group of statements that are enclosed within { } braces. They define the scope of the identifiers and are generally used to enclose the body of functions and control statements.

The body of the main function is from line #4 to line #9 enclosed within  { }.

Syntax:

{

// Body of the Function

return 0;
}

5. Semicolons

As you may have noticed by now, each statement in the above code is followed by a ( ; ) semicolon symbol. It is used to terminate each line of the statement of the program. When the compiler sees this semicolon, it terminates the operation of that line and moves to the next line.

Syntax:

any_statement ;

6. Identifiers

We use identifiers for the naming of variables, functions, and other user-defined data types. An identifier may consist of uppercase and lowercase alphabetical characters, underscore, and digits. The first letter must be an underscore or an alphabet.

Example:

int num1 = 24;
int num2 = 34;

num1 & num2 are the identifiers and int is the data type.

7. Keywords

In the C++ programming language, there are some reserved words that are used for some special meaning in the C++ program. It can’t be used for identifiers.

For example, the words int, return, and using are some keywords used in our program. These all have some predefined meaning in the C++ language.

There are total 95 keywords in C++. These are some keywords.

int           void          if            while          for           auto            bool        break

this static new true false case char class

To know more about Identifiers and Keywords in C++, refer to the article C/C++ Tokens.

8. Basic Output cout

In line #7, we have used the cout method which is the basic output method in C++ to output the sum of two numbers in the standard output stream (stdout).

Syntax:

cout << result << endl;

To know more about basic input and output in C++, please refer to the article – Basic Input and Output in C.

Now, we have a better understanding of the basic syntax structure of the above C++ program. Let’s try to execute this program and see if it works correctly.

C++
// C++ program to demonstrate the basic syntax
// Header File Library
#include <iostream>

// Standard Namespace
using namespace std;

// Main Function
int main()
{

    // Body of the Function

    // Declaration of Variable
    int num1 = 24;
    int num2 = 34;

    int result = num1 + num2;

    // Output
    cout << result << endl;

    // Return Statement
    return 0;
}

Output
58

The above program runs correctly and displays the specified output because we have followed the syntax rules of C++. We will learn more about these basic elements later.

Object-Oriented Programming in C++

C++ programming language supports both procedural-oriented and object-oriented programming. The above example is based on the procedural-oriented programming paradigm. So let’s take another example to discuss Object Oriented Programming in C++.

Structure of object oriented Program

1. Class

A class is a template of an object. For example, the animal is a class & dog is the object of the animal class. It is a user-defined data type. A class has its own attributes (data members) and behavior (member functions). The first letter of the class name is always capitalized & use the class keyword for creating the class.

In line #3, we have declared a class named Calculate and its body expands from line #3 to line #7.

Syntax:

class class_name{

// class body

};

To know more about classes in C++, please refer to this article.

2. Data Members & Member Functions

The attributes or data in the class are defined by the data members & the functions that work on these data members are called the member functions.

Example:

class Calculate{

public:
int num1 = 50; // data member
int num2 = 30; // data member

// member function
int addition() {
int result = num1 + num2;
cout << result << endl;
}
};

In the above example, num1 and num2 are the data member & addition() is a member function that is working on these two data members. There is a keyword here public that is access modifiers. The access modifier decides who has access to these data members & member functions. public access modifier means these data members & member functions can get access by anyone.

3. Object

The object is an instance of a class. The class itself is just a template that is not allocated any memory. To use the data and methods defined in the class, we have to create an object of that class.

They are declared in the similar way we declare variables in C++.

Syntax:

class_name object_name;

We use dot operator ( . ) for accessing data and methods of an object.

To know more about objects in C++, please refer to the article – C++ Classes and Objects.

Now, let’s execute our code to see the output of the program.

C++
#include <iostream>
using namespace std;

class Calculate{
    
      // Access Modifiers
    public:
          // data member
        int num1 = 50;
        int num2 = 30;
        
          // member function
        int addition() {
            int result = num1 + num2;
            cout << result << endl;
        }
};

int main() {
    
    // object declaration
    Calculate add;
      // member function calling
    add.addition();

    return 0;
}

Output
80


Previous Article
Next Article

Similar Reads

Syntax Error in C++
Syntax plays a vital role and even a slight mistake can cause a lot of unexpected errors. One of these errors is the "expected unqualified id error" or "expected unqualified id before ' ' token" which can arise due to some common oversights while writing your code. In this article, we are going to dive deep into the expected unqualified id error an
6 min read
Basic Input / Output in C++
C++ comes with libraries that provide us with many ways for performing input and output. In C++ input and output are performed in the form of a sequence of bytes or more commonly known as streams. Input Stream: If the direction of flow of bytes is from the device(for example, Keyboard) to the main memory then this process is called input.Output Str
5 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
7 ways to Initialize Vector in C++
Vectors in C++, like Arrays, are one of the most extensively used entities and to initialize vectors in C++ is one of the most common issues that users face. One of the most commonly used methods for vector initialization is the Array style. But C++, along with this, provides several different methods to initialize a vector. In this post, we have l
6 min read
30 OOPs Interview Questions and Answers (2024)
Object-Oriented Programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
Top 50 C++ Project Ideas For Beginners & Advanced
C++ is one of the most popular programming languages widely used in the software industry for projects in different domains like games, operating systems, web browsers, DBMS, etc due to its fast speed, versatility, lower-level memory access, and many more. Many top companies like Microsoft, Google, Apple, Netflix, etc use C++ to develop their produ
15+ min read
C++ Programming Examples
Writing C++ programs yourself is the best way to learn the C++ language. C++ programs are also asked in the interviews. This article covers the top practice problems for basic C++ programs on topics like control flow, patterns, and functions to complex ones like pointers, arrays, and strings. C++ Tutorial C++ Recent Articles Topics: Basic Programs
9 min read
C++ Interview Questions and Answers (2024)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as
15+ min read
Sorting a vector in C++
Prerequisites : std::sort in C++, vector in C++, initialize a vector in C++. C/C++ Code // C++ program to sort a vector in non-decreasing // order. #include &lt;bits/stdc++.h&gt; using namespace std; int main() { vector&lt;int&gt; v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; sort(v.begin(), v.end()); cout &lt;&lt; &quot;Sorted \n&quot;; for (auto x : v) cout
4 min read
Left Shift and Right Shift Operators in C/C++
In C/C++, left shift (&lt;&lt;) and right shift (&gt;&gt;) operators are binary bitwise operators that are used to shift the bits either left or right of the first operand by the number of positions specified by the second operand allowing efficient data manipulation. In this article, we will learn about the left shift and right shift operators. Le
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg