Hello, C + + (8) How do you express the amount of data that remains constant? 3.2.2 Constants

Source: Internet
Author: User
Tags alphanumeric characters

3.2.2 Constants

and variables can be used in the program to express those that may change the amount of data corresponding to, in C + +, we use constants to express those always remain unchanged data volume. In simple terms, the values, characters, strings, and const keyword modifiers used directly in the program. Most of the time, a constant needs to be read only once, so it has no name and can be used directly without a definition. And because its data can only be read and cannot be modified, it is often used to assign values to a variable or directly participate in the operation. For example:

// Assign the variable nHeight with the constant 180
nHeight = 180;
// directly use constants for calculations
fArea = fR * fR * 3.1415926; 

The "180" and "3.1415926" Here are two constants, which are used to assign values to the variable nheight and to participate in the multiplication operation. Such constants can only be used once, and when the assignment operation and multiplication are complete, the two constants are no longer meaningful.

Constants in C + + mainly include numeric constants (integer constants, floating-point constants), character constants, and string constants.

1. Integral type constant

Integer constants are integers that appear as text. The representation of an integer constant is the most common in decimal, or it can be expressed as octal or hexadecimal as needed. In the program, we can differentiate the various binary integers according to the prefix of the numbers.

L decimal integers: No prefixes, such as 0, 123,-1, and so on.

L octal integers: prefixed with 0, numbers do not contain 8 and 9. For example, 0123,-022 and so on.

L hexadecimal integer: prefixed with 0x or 0X, the number includes a~f six alphanumeric characters in addition to 0~9 10 digits. such as 0x123, -0x2 and so on.

In the program, we can directly use these three ways to represent an integer value:

nHeight = 173; // decimal constant
nHeight = 0255; // octal constant
nHeight = 0xAD; // hex constant 

The above code assigns values to a variable in different binary form constants. Although these constants behave differently, they represent a value of 173.

2. Floating-point constants

Floating-point constants are floating-point numbers that appear as text, which is what we usually call decimals. Floating-point numbers are expressed in two forms: decimal and exponential. The decimal form is our usual fractional notation, consisting of numbers and decimal points, such as 1.0, 0.1,. 123, and so on. The exponential form is a method of scientific notation, which represents a floating-point number as the product of how many times a decimal and 10 are multiplied. When a floating-point number is large or small, it is more convenient to use an exponential form to represent floating-point numbers. For example, 1.3e9 means 1.3x109, that is, 1300000000,0.123e-4 represents 0.123x10-4, and so on.

3. Character constants

Character constants are the single characters used in the program, such as "a", "a", "!" such as In C + +, we use single quotation marks (' ') to represent a character constant. For example:

// Assign aMark constant to variable aMark
char aMark = ‘A’;
// Output a character constant ‘! ’
cout << ‘!‘ << endl; 

In addition to the above common characters that can be displayed on the screen, C + + allows a class of special character constants to be used. These characters cannot be entered directly through the keyboard or directly to the screen, but can be used to indicate special control meanings, such as a computer bell (/a), a newline (/n), a carriage return (/R), and so on. These characters start with "\", meaning that the characters after "\" are converted to other meanings, so these characters are also called escape characters. Table 3-2 lists the common escape characters for C + +.

Table 3-2 Common escape characters in C + +

Escape character


' \a '

Bell, when the character is output directly with cout, the screen is not displayed, but the computer speaker emits a "drip" sound, which is commonly used to prompt the user program to complete an operation.

' \ n '

NewLine (n:line), if there is this character in a string, the string after the escape character wraps the output

(Do you remember that we used this escape character in the 2.2.2[chen1] section? Look Back! )

' \ t '

tab, the output position will move sideways one tab position

' \ r '

Enter (R:return)


The escape character "\" itself


Double quotes


Single quotation marks. These three escape characters are combined to output some strings that contain special symbols. For example, we want to output:

These characters start with "\"

Such a string, you need to use these escape characters to output the special symbols:

cout<< "These characters start with \" \\\ "<<endl;

The use of escape characters is similar to the use of a display character, where you can put an escape character in a string, let it do the appropriate control, or output an escape character individually, for example:

// put "\ n" into a string, it will control the output of this string to two lines
// Congratulations!
// mission completed!
cout << "Congratulations! \ nTask completed!" <endl;
// Directly output the "" \ a "escape character, send out a computer bell, prompting the user to complete the task
cout << ‘\ a‘ << endl; 

4. String constants

A string constant is a sequence of characters enclosed by a pair of double quotation marks (""), such as "Hello world!". Note that because double quotation marks are the bounds of a string, if you want to use double quotation marks in a string, you use the escape character to represent it. It is also worth reminding that the double quotes here must be in English (""). Because they are very similar in form to Chinese double quotation marks (""), they are often misused by beginners and result in errors. For example:

// Assign values to variables using string constants
strName = "ZengMei";
// output string constant
// When outputting some special symbols (such as double quotes, slashes, etc.), we must use corresponding escape characters
// The escape character "\" is used here to output double quotes in the string. The final output is as follows
// Your name is: "ZengMei"
cout << "Your name is: \" ZengMei \ "" << endl; 

Know more: Native string (Raw string) identity

In string constants, we can use the backslash (\) This escape operator to introduce special characters for special output purposes. However, this brings trouble to the writing of regular expressions, because in regular expressions, backslashes are used to introduce special symbols that represent characters and are used very frequently. If you want to represent the backslash character in a regular expression, we have to use two backslashes to represent a backslash character. For example, we want to express the pattern (\zeng\\\mei) of "two words separated by backslashes (\)" in C + + code:

"\\zeng\\\\\\mei"; // Such representations are not intuitive and error-prone   

We note that in regular expressions, the backslash character is expressed as a combination of two backslashes. To represent a backslash, we must use two backslashes in the regular expression to represent it. The first backslash indicates that this is an escape character, and the second represents a true backslash. This way of expression makes our strings very complicated and not intuitive, even experienced programmers are prone to error.

To solve this problem, c++11 introduces a primitive string mechanism and uses the native string identifier R to represent a native string. In the native string, each character nonalphanumeric represents its most primitive character meaning, WYSIWYG. In other words, the backslash (\) no longer has the function of an escape character, and a backslash can be represented with only a backslash. Thus, the above examples can be simplified to:

string s = R"(\zeng\\mei)"; // using the native string represented by R "()"    

Native string R "(...)" notation is a bit verbose compared to the ordinary string "..." notation, but its meaning is that it allows the escape rule in the string to be invalid, what is obtained, what you see is what you get. When we need to frequently represent various special symbols (backslashes, quotation marks, etc.) in a string, the native string will be very simple, and this little bit of writing is worthwhile.

Both numeric constants and string constants are like the "Lei Feng" of the C + + world, only doing good deeds without leaving a name. However, this also poses a problem: when we need to repeatedly use a constant in our program, we have to write the same constant over and over again in our code. For example, to write a calculation program about a circle, you will undoubtedly use the floating-point constant of 3.14159 multiple times:

float fR = 19.82; // radius
// Calculate area with constant 3.14159
float fArea = 3.14159 * fR * fR;
// Calculate the perimeter with the constant 3.14159
float fGirth = 2 * 3.14159 * fR; 

Such code is not only difficult to write (repeat the same decimal number repeatedly, it is difficult to guarantee correctness and consistency), it is difficult to maintain later (if you want to change this constant, we have to modify all the places used to this constant). All this is because the constant in the program is nameless, and each time is directly used to cause. The solution, then, is to give the constant a name so that we can easily repeat the same constant multiple times with this name. In C + +, there are two ways to take a name for a constant:

1. Define a numeric value or string macro with a # define precompiled directive, and then use the macro instead of the direct usage of the constant

2. Use the const keyword to modify a variable to be a constant variable, and then use the constant variable instead of the direct usage of the constant

Let's start by looking at how to use macros instead of constants. The so-called macro is the definition of a value with no definite meaning (for example, 3.14159, known as PI, not knowing that it is just some strange number) defined as a definite identifier (for example, Pi, which everyone would think of as Pi). You can then use this meaningful identifier in your code instead of a numeric value that is not explicitly meaningful, making your code more readable. In C + +, you can define a macro by using the # define precompiled directives:

Macro value #define Macro name

where "macro name" is the macro to be defined, it is usually represented by a meaningful name in uppercase. "Macro Value" is what this macro represents, it can be a constant, a string, or even a more complex statement. For example, you can define 3.14159 as a macro pi with the following statement:

define the 3.14159 macro Pi#define PI 3.14159 

With the corresponding macro pi for the constant 3.14159, we can use PI directly in the code instead of 3.14159 for the corresponding calculation. For example, the above code can be simplified to:

// Define 3.14159 as macro PI
#define PI 3.14159

float fR = 19.82; // radius
// Calculate area using PI
float fArea = PI * fR * fR;
// Calculate perimeter with PI
float fGirth = 2 * PI * fR; 

Here, the use of Pi instead of the original should be used 3.14159 is also possible to complete the calculation. So, how does a macro do this? The macro pi here does not really have the value of the 3.14159 constant that it represents, which is essentially a substitution. When the compiler is pre-compiling the code, it replaces the macro in the code with what it represents, in other words, the Pi in the code above is replaced with 3.14159, and the code that ultimately participates in the compilation is actually still:

// Macro PI is replaced with the constant 3.14159 to calculate the area
float fArea = 3.14159 * fR * fR;

// Macro PI is replaced with the constant 3.14159 to calculate the perimeter
float fGirth = 2 * 3.14159 * fR; 

As you can see from here, the use of macros does not reduce the constants in the code, but it uses a clever way to reduce the tedious repetition of entering a constant, avoiding possible typos.

Best Practice: Use macros to improve the readability and maintainability of your code

In addition to reducing code duplication to avoid writing errors, the use of macros gives us additional benefits:

1. Make the code more concise and more readable

A well-defined macro name tends to contain richer information than a complex and meaningless constant number, which increases the readability of the code, and makes the code more concise than a constant number. Compare the following two sections of code:

// code without macros
for (int i = 0; i <1024; ++ i)
     // ...

// code using macros
#define MIN 0
#define MAX 1024

for (int i = MIN; i <MAX; ++ i)
     // ...

By contrast, we can see that while two pieces of code implement the same functionality, the message to the code reader is not the same. The first piece of code simply means that the loop is from 0 to 1024, and as to why it is from 0 to 1024, only the code reader can guess for itself. The second code, through the use of macros, clearly tells us that this loop is between the minimum and maximum values, so that you can get richer information from the code itself, which increases the readability of the code.

2. Make your code easier to maintain

If we use a constant number directly in our code, and the exact number needs to be modified, then we have to modify all the places in the code that use that number. And if this constant is defined macro and a macro is used in the code instead of the constant, when we need to modify the constant, we just need to change the definition of the macro, without having to modify all the places in the code that use the macro. For example, we define the 3.14159 constant as the PI macro and use it to participate in the calculation, and when we need to reduce the accuracy using 3.14 for the calculation, simply modify the PI definition and define 3.14 as pi:

// Modify the definition of PI
#define PI 3.14

// Calculate area using 3.14 as pi
float fArea = PI * fR * fR; 

In addition to the macros defined by # define can represent constants, C + + also provides a const keyword that can be used to modify a variable to a constant value that cannot be modified, or to represent constants in the program.

The use of the Const keyword is simple, just to add the Const keyword before or after the data type when defining the variable:

Const data type constant variable name = constant value;

The CONST keyword here tells the compiler that the value of this variable is not modifiable (or, more strictly, it cannot be directly modified by the variable name, but indirectly by other means), which makes the variable have the most basic characteristic of a constant: it cannot be modified. So, after the modification of the const keyword, this variable becomes a constant variable that can be used to represent various constants in the program. It is important to note that because the value of a constant variable cannot be modified after it is defined, it must be assigned at the same time as the constant variable is defined. For example:

// define constant variable PI
const double PI = 3.14159;

// ...

// Calculate area with constant PI
float fArea = PI * fR * fR;
// Calculate perimeter with constant PI
float fGirth = 2 * PI * fR; 

After the definition, if you attempt to modify the value represented by this constant variable name, it will result in a compilation error, so that the value of the variable will not be modified and become a constant variable. For example, if you want to reduce the accuracy of pi in the program, Jerry-building is not possible:


Since both the macro and the Const keyword can be used to give a constant a birthright, how do you choose? Do you want to use a macro or a const keyword to represent a constant? Our answer is: You should choose to use the Const keyword more. For example, to represent the 3.14159 constant in a program, you can use the following two ways:

macro Mode #define PI 3.14159// const mode 3.14159;    

Both of these approaches are syntactically legal and are not much different in terms of use. But the second way is better than the first, because if you define this constant using # # macro PI,PI will be replaced by the precompiled processor in the pre-compilation phase of the code with the 3.14159 constant itself, so there is no compiler data type check, and the name of the macro does not appear in the symbol table , which can cause trouble with debugging later in the code, you might encounter a number, but you don't know where it came from, and that's what we often call magic number (numbers that don't know where it comes from, like magic). Instead, the constant is represented by a const variable, which has a data type that the compiler can check for data types to avoid errors. At the same time this constant variable name also appears in the program's symbol table, facilitates the debugging of the program. Therefore, we always prefer to use the Const keyword-decorated constant variable to represent constants in the program.

Original address: http://www.cnblogs.com/nihaoCPP/p/3972897.html

Hello, C + + (8) How do you express the amount of data that remains constant? 3.2.2 Constants

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.