C++ Basic Syntax
A C++ program can be defined as a collection of objects that interact by calling each other's methods. Now, let's briefly look at what classes, objects, methods, and instant variables are.
Object - Objects have states and behaviors. For example: the state of a dog - color, name, breed, behaviors - wagging, barking, eating. An object is an instance of a class.
Class - A class can be defined as a template/blueprint that describes the behavior/state that the object supports.
Method - Essentially, a method represents an action. A class can contain multiple methods. Logic can be written, data can be manipulated, and all actions can be executed within methods.
Instant Variables - Each object has its unique instant variables. The state of an object is created by the values of these instant variables.
C++ Program Structure
Let's look at a simple code that outputs the word Hello World.
Example
#include <iostream>
using namespace std;
// main() is where the program execution begins
int main()
{
cout << "Hello World"; // Prints Hello World
return 0;
}
Next, we will explain the above program:
C++ defines some header files that contain necessary or useful information for the program. In this program, the header file <iostream> is included.
The next line using namespace std; tells the compiler to use the std namespace. The concept of a namespace is relatively new in C++.
The next line // main() is where the program execution begins is a single-line comment. Single-line comments start with // and end at the end of the line.
The next line int main() is the main function where the program execution begins.
The next line cout << "Hello World"; will display the message "Hello World" on the screen.
The next line return 0; terminates the main() function and returns the value 0 to the calling process.
Compiling & Executing a C++ Program
Next, let's see how to save the source code in a file and 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 navigate to 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 will move to the next line and generate an a.out executable file.
Now, type 'a.out' to run the program.
You will see 'Hello World' displayed on the screen.
$ g++ hello.cpp $ ./a.out Hello World
Ensure that your path includes the g++ compiler and that you run it in the directory containing the source file hello.cpp.
You can also use a makefile to compile C/C++ programs.
Semicolons & Blocks in C++
In C++, a semicolon is a 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 set of logically connected statements enclosed by braces. For example:
{
cout << "Hello World"; // Prints Hello World
return 0;
}
C++ does not treat the end of a line as a terminator. Therefore, you can place multiple statements on a single line. For example:
x = y;
y = y + 1;
add(x, y);
is equivalent to
x = y; y = y + 1; add(x, y);
C++ Identifiers
C++ identifiers are names used to identify variables, functions, classes, modules, or any other user-defined items. An identifier starts with a letter A-Z or a-z or an underscore _ followed by zero or more letters, underscores, and digits (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.
Here are some valid identifiers:
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.
| asm | else | new | this | | auto | enum | operator | throw | | bool | explicit | private | true | | break | export | protected | try | | case | extern | public | typedef | This is a Chinese to English translation. Please provide the English translation for this text. Do not provide any explanations or text apart from the translation.
Chinese: | 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 | |
Complete keyword introduction can be found at: C++ Keywords (Reserved Words) Complete Introduction
Trigraphs
Trigraphs are three-character sequences that represent another character and are also known as trigraph sequences. Trigraph sequences always start with two question marks.
Trigraph sequences are not common, but the C++ standard allows certain characters to be specified as trigraph sequences. This was essential in the past to represent characters not available on the keyboard.
Trigraph sequences can appear anywhere, including strings, character sequences, comments, and preprocessor directives.
Below is a list of the most commonly used trigraph sequences:
Trigraph | Replacement | |
---|---|---|
??= | # | |
??/ | \ | |
??' | ^ | |
??( | [ | |
??) | ] | |
??! | ||
??< | { | |
??> | } | |
??- | ~ |
If you want two consecutive question marks in your source code and do not want them to be replaced by the preprocessor, this can occur in character constants, string literals, or program comments. Alternative methods include using string concatenation: "...?""?..." or escape sequences: "...?\?...".
Starting from Microsoft Visual C++ 2010, the compiler no longer automatically replaces trigraphs by default. If you need to use trigraph replacement (for compatibility with old software code), you need to set the compiler command line option /Zc:trigraphs.
g++ still supports trigraphs by default but issues a compiler warning.
Whitespace in C++
A line that contains only whitespace, possibly with a comment, is known as a blank line, and C++ compiler completely ignores it.
In C++, whitespace is used to describe blank spaces, tabs, newline characters, and comments. Whitespace separates the parts of a statement so that the compiler can identify where one element in a statement, such as int
, ends and the next element begins. Therefore, in the following statement:
int age;
Here, there must be at least one whitespace character (usually a space) between int
and age
so that the compiler can distinguish them. On the other hand, in the following statement:
fruit = apples + oranges; // Get the total number of fruits
The whitespace characters between fruit
and =
, or =
and apples
are not required, but you can add them as needed to improve readability.