C++ Syntax Basics
Code Framework
If you don't want to delve into the underlying principles, you can simply memorize this "framework" when starting out:
1 2 3 4 5 6 7 | |
What is include?
#include is actually a preprocessor directive, meaning to "place" a file at the location of this statement. The file being "placed" is called a header file. In other words, during compilation, the compiler will "copy" the content of the header file iostream and "paste" it at the #include <iostream> statement. This allows you to use objects like std::cin, std::cout, std::endl provided by iostream.
If you have learned C, you'll notice that the C++ header files we've encountered so far generally don't have the .h suffix, while those C language header files xx.h have become cxx, e.g., stdio.h becomes cstdio. This is because C++ uses C language header files directly for compatibility with C. To distinguish C++ header files from C header files, the c prefix is used.
Generally, you should determine which headers to #include based on the needs of the C++ program you are writing. However, if you #include extra headers, it will only increase compilation time and has almost no impact on runtime. So far, we have only encountered the iostream and cstdio headers. If you only need scanf and printf, you don't need to #include <iostream>.
Can you #include your own header files? Yes, you can.
You can write your own header file, e.g., myheader.h. Then, place it in the same directory as your code and #include "myheader.h". Note that custom header files need to use quotes instead of angle brackets. Of course, you can also use the compilation command -I <header_file_path> to tell the compiler where to find the header file, so you don't need to place the header file in the same directory as your code.
What is main()?
You can understand it as the code inside main() will be executed when the program runs.
Actually, the main function is called by the system or an external program. For example, when you call your program from the command line, you are calling the main function in your program (after constructing global variables).
The final return 0; indicates the program ran successfully. By default, returning 0 at the end of the program indicates everything is normal; otherwise, the return value represents an error code (on Windows, the hexadecimal of this error code can be queried via the Windows Error Codes website). Who receives this return value? It's the system or external program that called your program; it will receive this return value when your program ends. If you don't write a return statement, the default return value for normal program termination is also 0.
In C or C++, a program return value not equal to 0 will cause a runtime error (RE).
Comments
In C++ code, there are two ways to write comments:
-
Inline comments
Start with
//. Everything after//on that line is a comment. -
Comment block
Start with
/*and end with*/. Everything in between is a comment, which can span multiple lines.
Comments have no effect on program execution. They can be used to explain the program's meaning or to temporarily disable a block of code (while keeping it in the source file).
In software engineering, comments facilitate future maintenance and reading by others.
In OI, few people write many comments, but comments can help clarify your thinking while coding or aid in reviewing later. Moreover, if you are writing solutions or tutorials, appropriate comments can help readers understand the code's intent. We hope students can develop the good habit of writing comments.
Input and Output
cin and cout
1 2 3 4 5 6 7 8 | |
What is a variable?
You can refer to the Variables page.
What is std?
std is the namespace used by the C++ standard library. Namespaces are used to avoid naming conflicts.
For detailed knowledge about namespaces, refer to the Namespaces page.
scanf and printf
scanf and printf are actually functions provided by the C language. In most cases, they are faster than cin and cout, and they offer convenient control over input/output formatting.
Input/Output Optimization
For the specific differences between cin/cout and scanf/printf and input/output optimization, please refer to the Input/Output Optimization page.
1 2 3 4 5 6 7 8 | |
Here, %d indicates the variable being read/output is a signed integer (int).
Similarly:
%sindicates a string.%cindicates a character.%lfindicates a double-precision floating-point number (double).%lldindicates a long integer (long long). Depending on the system, it might also be%I64d.%uindicates an unsigned integer (unsigned int).%lluindicates an unsigned long integer (unsigned long long), which might also be%I64u.
Besides type specifiers, there are also ways to control formatting. Many are not commonly used; two commonly used ones are listed below:
%1dindicates an integer of length 1. When reading, it can read digits one by one even without spaces. When outputting, if the specified length is greater than the number of digits, the number will be padded with spaces in front. If the specified length is less than the number of digits, it has no effect.%.6lf, used for output, retains six decimal places.
You can fill in other numbers in the corresponding places of these two operators, e.g., %.3lf means retain three decimal places.
What are 'double-precision floating-point numbers' and 'long integers'?
These represent variable types. As above, they will be explained uniformly in Variables.
Why is there an & operator in scanf?
Here, & is actually the address-of operator, returning the variable's address in memory. scanf receives the variable's address as a parameter. This might only be fully explained in Pointers, but for now, just remember it.
What is \n?
\n is an escape character, representing a newline.
Escape characters are used to represent characters that cannot be directly input, such as newline characters that cannot be directly input within string literals due to line breaks, quotes that cannot be input due to their special meaning, and backslashes that cannot be input because they represent escape characters.
Commonly used escape characters include:
-
\trepresents a tab character. -
\\represents\. -
\"represents". -
\0represents the null character, used to mark the end of a C-style string. -
\rrepresents carriage return. In Linux, the newline character is\n; in Windows, it's\r\n. In OI, if output needs a newline, using\nis sufficient. However, when reading input character by character, newline characters might cause issues, so be careful. For example,getstreats\nas the end of a string. If the newline is\r\n, the\rwill remain at the end of the string. -
Specifically,
%%represents%, and can only be used inprintforscanf. In other string literals, simply use%.
What is a literal?
A "literal" is a segment of code that directly represents a value, e.g., 3 is an int literal, 'c' is a char literal. The "hello world" we wrote in the program above is also a string literal.
Unexplained, seemingly arbitrary literals are also called "magic numbers," which is highly discouraged if the code needs to be read by others.
Some Extended Content
Whitespace Characters in C++
In C++, all whitespace characters (spaces, tabs, newlines), whether multiple or single, are treated as the same. (Of course, those inside quotes as part of a string don't count.)
Therefore, you can freely use any coding style (except inline comments, string literals, and preprocessor directives must be on a single line), for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
However, this is not recommended.
Another widely used but different from the OI Wiki required coding style:
1 2 3 4 5 6 7 8 9 10 11 | |
#define Directive
#define is a preprocessor directive used to define macros, essentially performing text replacement. For example:
1 2 3 4 5 6 7 8 9 10 11 | |
What is an identifier?
An identifier is a set of characters that can be used as a variable name. For example, abcd and abc1 are valid identifiers, while 1a and c+b are not.
Identifiers start with a letter or underscore and can only contain letters, underscores, and digits. Notably, keywords (like int, for, if) cannot be used as identifiers.
What is a preprocessor directive?
Preprocessor directives are commands accepted by the preprocessor, used for preliminary text transformation of the code, such as file inclusion #include and macro processing #define. For GCC, the output .i file from the preprocessing stage is not kept by default. You can use the -E option to keep the output file.
Macros can take parameters. Parameterized macros can be used like functions:
1 2 3 4 5 6 7 | |
However, parameterized macros differ from functions. Because macros are text replacements, they can cause many issues. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
Using #define is risky (since its scope is the entire program, it may cause unintended text replacement; use #undef to cancel the definition promptly). Therefore, it should be used cautiously. The recommended approach is: use the const qualifier to declare constants and use functions instead of macros.
However, in OI, #define still has its uses (the following two are not recommended as they reduce code standardization):
#define int long long+signed main(). Often used to avoid errors from forgetting to uselong long, or to rule out the possibility of such errors during debugging. (May also increase constant time or cause TLE, or cause MLE due to memory overflow.)#define For(i, l, r) for (int i = (l); i <= (r); ++i),#define pb push_back,#define mid ((l + r) / 2), used to shorten code length.
However, #define also has advantages. For example, combined with preprocessor directives like #ifdef, it can be very effective:
1 2 3 4 5 | |
You can control the compiled code via -DLINUX during compilation without modifying the source file. This has another advantage: the executable compiled with -DLINUX does not contain code for other operating systems; that code was removed during preprocessing.
#define can also use the # and ## operators, greatly facilitating debugging.
本页面最近更新:,更新历史
发现错误?想一起完善? 在 GitHub 上编辑此页!
本页面贡献者:OI-wiki
本页面的全部内容在 CC BY-SA 4.0 和 SATA 协议之条款下提供,附加条款亦可能应用