C++ basic syntax


C++ program can be defined as a collection of objects that interact by calling each other's methods. Now let us briefly look at what are classes, objects, methods, and instant variables.

  • Object - Objects have state and behavior. For example: a dog's status - color, name, breed, behavior - shake, bark, eat. Objects are instances of classes.

  • Classes - Classes can be defined as templates/blueprints that describe the behavior/state of an object.

  • Method - Basically, a method represents a behavior. A class can contain multiple methods. You can write logic, manipulate data, and perform all actions in methods.

  • Immediate Variables - Each object has its own unique instant variables. The object's state is created from the values ​​of these instant variables.

C++ Program Structure

Let us look at a simple code that can output the word Hello World.

#include <iostream>
using namespace std;

// main() 是程序开始执行的地方

int main()
{
   cout << "Hello World"; // 输出 Hello World
   return 0;
}

Next let’s explain the above program:

  • The C++ language defines some header files, which contain necessary or useful information in the program. . The above program includes the header file <iostream>.

  • Line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively new concept in C++.

  • Next line // main() is where the program starts execution is a single line comment. Single-line comments begin with // and end at the end of the line.

  • Next line int main() is the main function, and the program execution starts from here.

  • Next line cout << "Hello World"; will display the message "Hello World" on the screen.

  • Next line return 0; Terminate the main() function and return the value 0 to the calling process.

Compiling & Executing C++ Programs

Next let’s see how to save the source code in a file, and how to compile and run it. Here are the simple steps:

  • Open a text editor and add the above code.

  • Save the file as hello.cpp.

  • Open the command prompt and enter the directory where the file is saved.

  • Type 'g++ hello.cpp' and press Enter to compile the code. If there are no errors in the code, the command prompt jumps to the next line and generates the a.out executable file.

  • Now, type ' a.out' to run the program.

  • You can see 'Hello World' displayed on the screen.

$ g++ hello.cpp
$ ./a.out
Hello World

Make sure you have the g++ compiler in your path, and make sure you are running it in the directory containing the source file hello.cpp.

You can also use makefile to compile C/C++ programs.

Semicolon & Block in C++

In C++, the semicolon is the statement terminator. That is, each statement must end with a semicolon. It indicates the end of a logical entity.

For example, here are three different statements:

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

A block is a group of logically connected statements enclosed in curly braces. For example:

{
   cout << "Hello World"; // 输出 Hello World
   return 0;
}

C++ does not end with end-of-line identifiers, so you can put multiple statements on one line. For example:

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

is equivalent to

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

C++ identifier

C++ identifier is used to identify variables, functions, classes, modules, or any other user-defined items name. An identifier begins with the letters A-Z or a-z or the underscore _, followed by zero or more letters, underscores, and numbers (0-9).

Punctuation characters such as @, $, and % are not allowed within C++ identifiers. C++ is a case-sensitive programming language. Therefore, in C++, Manpower and manpower are two different identifiers.

Several valid identifiers are listed below:

mohd       zara    abc   move_name  a_123
myname50   _temp   j     a23b9      retVal

C++ Keywords

The following table lists the reserved words in C++. These reserved words cannot be used as constant names, variable names, or other identifier names.

##auto enumoperatorthrow##boolbreakcase##catchfalseregister typeidcharfloatreinterpret_casttypenameclassforreturnunionfriendgotoifinlineintlongmutablenamespaceTrigram
asmelsenewthis
explicitprivatetrue
exportprotectedtry
externpublictypedef
##const
shortunsignedconst_cast
signedusingcontinue
sizeofvirtualdefault
staticvoiddelete
static_castvolatiledo
structwchar_tdouble
switchwhiledynamic_cast
template
Trigram is a sequence of three characters used to represent another character, also known as a three-character sequence. Three-character sequences always begin with two question marks.

Three-character sequences are less common, but the C++ standard allows certain characters to be specified as three-character sequences. In the past, this was an essential method to represent characters that were not available on the keyboard.

Three-character sequences can appear anywhere, including strings, character sequences, comments, and preprocessing directives.

The most commonly used three-character sequences are listed below:

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

All compilers do not support three-character groups. To avoid confusion, it is not recommended to use three-character groups.

Spaces in C++

Lines that contain only spaces are called blank lines and may be commented, and the C++ compiler will ignore them completely.

In C++, spaces are used to describe whitespace, tabs, newlines, and comments. Whitespace separates parts of a statement, allowing the compiler to identify where one element in the statement (such as an int) ends and the next element begins. So, in the following statement:

int age;

Here, there must be at least one space character (usually a whitespace character) between int and age so that the compiler can distinguish them. On the other hand, in the following statement:

fruit = apples + oranges;   // 获取水果的总数

The space character between fruit and =, or = and apples is not required, but you can add some spaces if needed to enhance readability.