If you're just starting out with C++, the first basic information we need to understand includes setting up the environment and basic C++ syntax. To learn more about basic C++ syntax, readers can also refer to the following C++ lesson by Mytour.
Basic C++ syntax
Article Contents
1. Structure of C++ Programs
2. Comments in C++ Programs
3. Creating Classes in C++
4. C++ Keywords
C++ Program Structure
To understand the structure of a C++ program, readers can refer to the example for printing 'Tamienphi.vn' below:
#include
using standard namespace;
primary function
{
display input and output
}
Header files are placed at the beginning, similar to in C programs. In the example above, iostream is a header file, providing input and output streams. Header files contain function libraries declared beforehand, which users can easily utilize.
Using namespace std informs the compiler to use the standard namespace. Namespaces collect identifiers used for classes, objects, and variables.
In a program, we can use namespaces in 2 ways: either by using the using command at the beginning, as in the example program above, or by using the namespace as a prefix before the identifier using the (::) operator.
For example: std::cout <>
main() is the function that holds the execution part of the program with a return type of int.
cout is used to print anything on the screen, similar to print in the C programming language. cin and cout are similar to scanf and printf, except that you don't need to mention Format Specifiers like %d for int, in cout & cin.
Comment in C++ Program
For single-line comments, we use // before mentioning the comment, as shown in the example below:
cout<'single line';=''>
For multi-line comments, we place the comment within /* and */.
/*this is
Mytour
comment */
Creating Classes in C++
Class names must begin with a capital letter and contain data variables as well as member functions.
Here is an example of creating classes in C++:
This is also a way to define classes; after the class is defined, objects and member functions will be used.
Variables can be declared anywhere in the program, but must be declared before being used. Therefore, we don't need to declare variables when starting the program.
C++ Keywords
Every programming language has its own set of keywords, and C++ is no exception. Each keyword has its own meaning, and programmers cannot alter them.
Below is a table listing the keywords in C++:
An important note is that we cannot use these keywords to name constants, variables, and identifiers.
This article introduces you to the basic syntax of C++ by Mytour. Additionally, readers can refer to other articles on Mytour to learn more about how to set up the C++ environment.