C++ Basic Syntax

C++ Basic Syntax (Full Explanation)

C++ Basic Syntax


When we think about a C++ program, it can be described as a set of objects that interact by calling each other's methods. Now, let's take a moment to explore the meanings of class, object, method, and instance variable.

  • Object − Objects possess states and behaviors. For instance, a dog has states (such as color, name, breed) and behaviors (like wagging, barking, eating). An object represents an instance of a class.
  • Class − A class serves as a template or blueprint that outlines the behaviors or states that objects of its type can exhibit.
  • Methods − A method essentially represents a behavior. A class can include multiple methods. It is within these methods that logic is implemented, data is processed, and all actions are carried out.
  • Instance Variables − Each object has its own distinct set of instance variables. The state of an object is determined by the values assigned to these instance variables.

C++ Program Structure

The fundamental structure of a C++ program comprises the following components:

  • Header file inclusion section: This section includes all necessary header files whose functions will be utilized in the program.
  • Namespace section: This section is where we declare the namespace.
  • The main() section: Here, we write our main code. The main() function serves as the entry point for any C++ program, marking the start of execution.

To delve deeper, read: C++ Hello, World Program.

Example

Let's examine a simple code snippet that prints the phrase Hello World.

#include <iostream>
using namespace std;

// main() is where program execution begins.
int main() {
   cout << "Hello World"; // prints Hello World
   return 0;
}

Example Explanation

Now, let's analyze the different components of the program above −

  • The C++ language specifies several headers that provide essential or helpful information for your program. For this particular program, the header <iostream> is required.
  • The line using namespace std; instructs the compiler to utilize the std namespace. Namespaces are a relatively new feature in C++.
  • The subsequent line '// main() is where program execution begins.' is a single-line comment in C++. Single-line comments start with // and continue until the end of the line.
  • The line int main() marks the main function where the execution of the program starts.
  • The following line cout << "Hello World"; triggers the display of the message "Hello World" on the screen.
  • The subsequent line return 0; concludes the main() function and sends the value 0 back to the calling process.

Compile and Execute C++ Program

Let’s explore how to save the file, compile, and run the program. Please adhere to the steps outlined below −

  • Begin by opening a text editor and inputting the code as shown above.
  • Save the file with the name: hello.cpp
  • Next, open a command prompt and navigate to the directory where you saved the file.
  • Enter 'g++ hello.cpp' and hit enter to compile your code. If your code is error-free, the command prompt will move to the next line and create an a.out executable file.
  • Now, type 'a.out' to execute your program.
  • You should see ' Hello World ' displayed on the window.
$ g++ hello.cpp
$ ./a.out
Hello World

Ensure that g++ is included in your path and that you are executing it in the directory containing the hello.cpp file.

You can also compile C/C++ programs using a makefile. For further information, refer to our 'Makefile Tutorial'.

Semicolons and Blocks in C++

In C++, a semicolon serves as a statement terminator. This means that every single statement must conclude with a semicolon, indicating the end of one logical unit.

For instance, here are three distinct statements −

x = y;
y = y + 1;
add(x, y);

A block consists of a series of logically connected statements enclosed by opening and closing braces. For example −

{
   cout << "Hello World"; // prints Hello World
   return 0;
}

C++ does not treat the end of a line as a terminator. Therefore, the placement of a statement within a line is inconsequential. For instance −

x = y;
y = y + 1;
add(x, y);

is equivalent to

x = y; y = y + 1; add(x, y);

C++ Identifiers

A C++ identifier is a name that identifies a variable, function, class, module, or any other user-defined item. An identifier must begin with a letter (A to Z or a to z) or an underscore (_), followed by zero or more letters, underscores, and digits (0 to 9).

C++ does not permit punctuation characters like @, $, and % in identifiers. It is a case-sensitive programming language, meaning that Manpower and manpower are recognized as distinct identifiers in C++. 

Here are some examples of valid identifiers −

mohd       zara    abc   move_name  a_123
myname50   _temp   j     a23b9      retVal

C++ Keywords

The list below outlines the reserved words in C++. These words cannot be utilized as constant names, variable names, or any other type of identifier. 

asmelsenewthis
autoenumoperatorthrow
boolexplicitprivatetrue
breakexportprotectedtry
caseexternpublictypedef
catchfalseregistertypeid
charfloatreinterpret_casttypename
classforreturnunion
constfriendshortunsigned
const_castgotosignedusing
continueifsizeofvirtual
defaultinlinestaticvoid
deleteintstatic_castvolatile
dolongstructwchar_t
doublemutableswitchwhile
dynamic_castnamespacetemplate

Trigraphs

Certain characters can be represented by an alternative form known as a trigraph sequence. A trigraph consists of three characters that stand for a single character, always beginning with two question marks. 

Trigraphs can be expanded wherever they occur, including within string literals, character literals, comments, and preprocessor directives. 

Below are the most commonly used trigraph sequences −

TrigraphReplacement
??=#
??/\
??'^
??([
??)]
??!|
??<{
??>}
??-~

Not all compilers support trigraphs, and their use is discouraged due to their potential for confusion. 

Whitespace in C++

A line that contains only whitespace, possibly accompanied by a comment, is referred to as a blank line, which the C++ compiler completely ignores. 

In C++, whitespace refers to spaces, tabs, newline characters, and comments. It serves to separate different parts of a statement, allowing the compiler to recognize where one element, such as int, concludes and where the next element begins. 

Statement 1

In the first statement, there must be at least one whitespace character (typically a space) between int and age for the compiler to differentiate them. 

int age;

Statement 2

In the second statement, no whitespace characters are required between fruit and =, or between = and apples, although you may choose to add some for clarity. 

fruit = apples + oranges;   // Get the total fruit

C++ Program Structure with Object-oriented Approach

C++ also embraces the object-oriented programming paradigm alongside the procedural programming model.

Example

This example illustrates a C++ program that utilizes an object-oriented approach.

#include <iostream>
using namespace std;

class Numbers {
 private:
  int a;
  int b;

 public:
  // Function to set values
  void setValues(int x, int y) {
    a = x;
    b = y;
  }

  // Function to add these numbers
  double addition() { return a + b; }

  // Function to display values
  void display() { cout << "a: " << a << ", b: " << b << endl; }
};

int main() {
  // Create an object of Numbers class
  Numbers num;

  // Set values
  num.setValues(10, 20);

  // Display the values
  num.display();

  // Find the addition
  int sum = num.addition();
  cout << "Sum of numbers: " << sum << endl;

  return 0;
}

Parts of C++ Program Structure with Object-oriented Approach

The various components of the C++ program structure that employ an object-oriented approach are outlined below:

1. Class Declaration

A class serves as a blueprint for an object, or in other words, it acts as a factory for creating objects. It represents a custom data type, allowing you to design a structure for an object.

A class declaration consists of the following elements:

  • Access modifiers: C++ includes three types of access modifiers: private, public, and protected. These modifiers determine the accessibility of data members and member functions.
  • Data members and member functions: The variables defined within the class declaration are referred to as data members, while the functions that operate on these data members are known as member functions.

Example

Referring to the previous example, the following section pertains to the declaration of a class –

class Numbers {
 private:
  int a;
  int b;

 public:
  // Function to set values
  void setValues(int x, int y) {
    a = x;
    b = y;
  }

  // Function to add these numbers
  double addition() { return a + b; }

  // Function to display values
  void display() { cout << "a: " << a << ", b: " << b << endl; }
};

The data members listed below are defined under the private access modifier, meaning these members can only be accessed by the member functions within the class –

private:
  int a;
  int b;

The following are the member functions utilized in the class –

void setValues(int x, int y);
double addition();
void display();

2. Object Creation

In the previous example, the statement below represents the object creation statement −

Numbers num;