Thank you for your likes, favorites, comments, triple support
C++ Basic Syntax
A C++ program can be defined as a collection of objects that interact by calling each other's methods. Let us now briefly look at what is a class, object, method, instant variable.
- Object - Objects have state and behavior. For example: a dog's state - color, name, breed, behavior - shaking, barking, eating. Objects are instances of classes.
- 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. Methods can be used to write logic, manipulate data, and perform all actions.
- Instant Variables - Each object has its own unique instant variables. The state of the object is created from the values of these immediate variables.
C++ program structure
Let's look at a simple piece of code that outputs the word Hello World .
example
#include <iostream> using namespace std; // main() is where the program starts int main() { cout << "Hello World"; // output Hello World return 0; }
Next, let's explain the above program:
- The C++ language defines some header files that contain necessary or useful information in the program. In the above program, the header file <iostream> is included .
- 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 one-line comment. Single-line comments begin with // and end at the end of the line.
- The next line int main() is the main function, and the program starts to execute from here.
- 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.
Compile & execute 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 a command prompt and change to the directory where you saved the file.
- Type 'g++ hello.cpp' and press Enter to compile the code. If there are no errors in the code, the command prompt skips to the next line and generates the a.out executable.
- 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 be sure to run it from the directory containing the source file hello.cpp.
You can also use makefiles to compile C/C++ programs.
Semicolon & block 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 statement block is a group of logically connected statements enclosed in curly braces. For example:
{ cout << "Hello World"; // output Hello World return 0; }
C++ does not identify end-of-line characters, so you can place multiple statements on a line. For example:
x = y; y = y+1; add(x, y);
Equivalent to
x = y; y = y+1; add(x, y);
C++ identifier
A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier begins with the letters AZ or az or the 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.
Several valid identifiers are listed below:
mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal
C++ keywords
The following table lists 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 |
A complete introduction to keywords can be found at: Complete Introduction to C++ Keywords (Reserved Words)
trigram
A trigram is a sequence of three characters used to represent another character, also known as a trigram. Three-character sequences always begin with two question marks.
Three-character sequences are less common, but the C++ standard allows certain characters to be designated as three-character sequences. In the past, this was an essential method to represent characters that were not on the keyboard.
Three-character sequences can appear anywhere, including strings, character sequences, comments, and preprocessing directives.
The most common three-character sequences are listed below:
trigram | replace |
---|---|
??= | # |
??/ | \ |
??' | ^ |
??( | [ |
??) | ] |
??! | | |
??< | { |
??> | } |
??- | ~ |
If you want to have two consecutive question marks in the source program, and do not want to be replaced by the preprocessor, this situation occurs in character constants, string literals, or program comments, the alternative is to use the automatic concatenation of strings : "...?" "?..." or escape sequence: "...?\?...".
Starting with Microsoft Visual C++ version 2010, the compiler no longer automatically replaces trigrams by default. If you need to use trigraph replacement (such as for compatibility with ancient software code), you need to set the compiler command line option /Zc:trigraphs
g++ still supports trigrams by default, but compile warnings will be given.
Spaces in C++
Lines containing only whitespace, known as blank lines, may be commented, and the C++ compiler ignores it entirely.
In C++, whitespace is used to describe blanks, tabs, newlines, and comments. Spaces separate parts of a statement, allowing the compiler to recognize where an element in the statement (such as an int) ends and 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 for the compiler to be able to distinguish them. On the other hand, in the following statement:
fruit = apples + oranges; // Get the total number of fruits
The space characters between fruit and =, or = and apples are not required, but you can add some spaces as needed for readability.
C++ comments
A program's comments are explanatory statements that you can include in your C++ code to improve the readability of your source code. All programming languages allow some form of comments.
C++ supports single-line comments and multi-line comments. All characters in comments are ignored by the C++ compiler.
There are generally two types of C++ comments:
-
// - Generally used for single line comments.
-
/* ... */ - Generally used for multi-line comments.
Comments start with // and end at the end of the line. For example:
example
#include <iostream> using namespace std; int main() { // this is a comment cout << "Hello World!"; return 0; }
It can also be placed after the statement:
example
#include <iostream> using namespace std; int main() { cout << "Hello World!"; // 输出 Hello World! return 0; }
When the above code is compiled, the compiler ignores // this is a comment and // prints Hello World!, resulting in the following result:
Hello World!
C++ comments start with /* and end with */. For example:
#include <iostream> using namespace std; int main() { /* This is a comment */ /* C++ comments can also * span lines */ cout << "Hello World!"; return 0; }
Inside /* and */ comments, the // characters have no special meaning. Inside // comments, the /* and */ characters also have no special meaning. So you can nest one kind of annotation inside another kind of annotation. For example:
/* Comments for outputting Hello World cout << "Hello World"; // Outputting Hello World */