C++ Basic Syntax
A 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 classes, objects, methods, and instance variables are.
- Object -Objects have 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 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.
- Instance variable -Each object has its own unique instance variables. The state of an object is created by the values of these instance variables.
C++ Program Structure
Let's look at a simple piece of code that can output the wordHello World。
Example
Next, we explain the above program:
- The C++ language defines some header files that contain information that is necessary or useful in the program. In the above program, the header file is included<iostream>。
- Next lineusing namespace std;Tell the compiler to use the std namespace. Namespace is a relatively new concept in C++.
- Next line// main() is where the program starts executingIs a single-line comment. A single-line comment starts with // and ends at the end of the line.
- Next lineint main()Is the main function, from which the program starts executing.
- Next linecout << "Hello World";Will display the message "Hello World" on the screen.
- Next linereturn 0;Terminates the main() function and returns the value 0 to the calling process.
Compile & Execute C++ Program
Next, let's take a look at 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 a command prompt and go to the directory where the file is saved.
- Type 'g++ hello.cpp', press Enter, and compile the code. If there are no errors in the code, the command prompt will jump to the next line and generate 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
Please make sure the g++ compiler is included in your path, and make sure you run it in the directory containing the source file hello.cpp.
You can also use a makefile to compile C/C++ programs.
Semicolons & Statement 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, the following are three different statements:
A statement block is a group of logically connected statements enclosed in curly braces. For example:
C++ does not use the end of a line as the terminator, so you can place multiple statements on one line. For example:
Equivalent to
C++ Identifiers
A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. 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 in C++ identifiers. C++ is a case-sensitive programming language. Therefore, in C++,Manpowerandmanpowerare two different identifiers.
The following are several 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 |
| 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, please refer to: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 starts with two question marks.
Trigraph sequences are not very common, but the C++ standard allows certain characters to be specified as trigraph sequences. In the past, this was an essential method to represent characters that were not available on the keyboard.
Trigraph sequences can appear anywhere, including strings, character sequences, comments, and preprocessor directives.
The most commonly used trigraph sequences are listed below:
| Trigraphs | replace |
|---|---|
| ??= | # |
| ??/ | \ |
| ??' | ^ |
| ??( | [ |
| ??) | ] |
| ??! | | |
| ??< | { |
| ??> | } |
| ??- | ~ |
If you want two consecutive question marks in the source program, and you do not want them to be replaced by the preprocessor, this situation occurs in character constants, string literals, or program comments. An alternative is to use automatic string concatenation: "...?""?..." or an escape sequence: "...?\?...".
Starting from Microsoft Visual C++ 2010, the compiler no longer replaces trigraphs by default. If you need to use trigraph replacement (for example, to be compatible with old software code), you need to set the compiler command-line option /Zc:trigraphs.
g++ still supports trigraphs by default, but will give a compilation warning.
Spaces in C++
A line containing only spaces, possibly with a comment, is called a blank line; the C++ compiler ignores it completely.
In C++, whitespace is used to describe spaces, tabs, newlines, and comments. Whitespace separates the parts of a statement, allowing the compiler to recognize where one element in a statement (such as int) ends and where the next element begins. Therefore, in the following statement:
int age;
Here, there must be at least one space character (usually a whitespace) between int and age, so that the compiler can distinguish them. On the other hand, in the following statement:
fruit = apples + oranges; // 获取水果的总数
The space characters between fruit and =, or between = and apples, are not required, but for better readability, you can add some spaces as needed.
other extensions