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 - An object has state and behavior. For example: a dog's state—color, name, breed; behavior—wagging, barking, eating. An object is an instance of a class.
- Class - A class can be defined as a template/blueprint that describes an object's behavior/state.
- Method - Basically, a method represents a behavior. A class can contain multiple methods. You can write logic, manipulate data, and perform all actions within methods.
- Instant variable - Each object has its own unique instant variables. An object's state is created by the values of these instant variables.
C++ Program Structure
Let's look at a simple piece of code that can output the word Hello World.
Example
#include
<
iostream
using
namespace
std;
// main() is where program execution begins
int
main
(
)
{
cout
<<
"
Hello World
"
;
// output Hello World
return
0
;
}
Next, let's explain the program above:
- The C++ language defines several header files that contain necessary or useful information for the program. In the program above, the header file
. - The next line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively new concept in C++.
- The next line // main() is where program execution begins is a single-line comment. A single-line comment starts with // and ends at the end of the line.
- The next line int main() is the main function, where program execution begins.
- The next line cout << "Hello World"; displays 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 how to compile and run it. Here are the simple steps:
- Open a text editor and add the code above.
- 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 moves to the next line and generates the 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
Make sure the g++ compiler is included in your path, and 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, every 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 braces. For example:
{
cout
<<
"
Hello World
"
;
// output Hello World
return
0
;
}
C++ does not use the end of a line as a terminator, so you can place 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++ 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 table below 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 |
| 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 |
For a complete introduction to keywords, see:Complete Introduction to C++ Keywords (Reserved Words)
Trigraphs
A trigraph is a sequence of three characters used to represent another character, also called a trigraph sequence. A trigraph sequence always begins with two question marks.
Trigraph sequences are uncommon, but the C++ standard allows certain characters to be designated as trigraph sequences. Previously, this was an essential method for representing characters not found on the keyboard.
Trigraph sequences can appear anywhere, including strings, character sequences, comments, and preprocessor directives.
The following lists the most commonly used trigraph sequences:
| Trigraphs | Replacement |
|---|---|
| ??= | # |
| ??/ | \ |
| ??' | ^ |
| ??( | [ |
| ??) | ] |
| ??! | | |
| ??< | { |
| ??> | } |
| ??- | ~ |
If you want two consecutive question marks in the source program without being replaced by the preprocessor—which occurs in character constants, string literals, or program comments—the optional solution is to use automatic string concatenation: "...?""?..." or an escape sequence: "...??...".
Starting with Microsoft Visual C++ 2010, the compiler no longer automatically replaces trigraphs by default. If you need to use trigraph replacement (e.g., for compatibility with legacy software code), you need to set the compiler command-line option /Zc:trigraphs
g++ still supports trigraphs by default, but issues a compilation warning.
Whitespace in C++
A line containing only whitespace, possibly with a comment, is called a blank line, and the C++ compiler completely ignores it.
In C++, whitespace refers to blanks, tabs, newlines, and comments. Whitespace separates the parts of a statement, allowing the compiler to recognize where one element (such as int) ends and the next begins. Therefore, in the following statement:
int age;
Here, there must be at least one whitespace character (usually a blank) between int and age so the compiler can distinguish them. On the other hand, in the following statement:
fruit = apples + oranges; // 获取水果的总数
the whitespace between fruit and =, or between = and apples, is not required, but you can add some whitespace as needed to improve readability.