Hello, C + + (10) Did you pass the C + + exam this time? Boolean data types that represent logical judgments in C + +

Source: Internet
Author: User
Tags alphabetic character control characters


3.4 Boolean Type


In our daily life, we need to use a variable of type int to represent bus 216; A variable of type float is required to represent 3.5 yuan a pound of tomato, and sometimes it needs to represent a data, which is the logical state:



"Have you passed the C + + exam this time?" ”



"Does he really love me?" ”



The "over-and-over" and "love-not-love" are all representations of a logical judgment. Compared with the bus line and the price of tomato which we used to represent in the numerical data type, there are many different values, and the logic judgment state has the particularity of "either or". For exam status, either "over" or "not", both must be selected. Because of this, in C + +, we also use a special data type--Boolean type--to express this "either" or "logical judgment State." Variables of the Boolean type can only be given a value of TRUE or FALSE, respectively, to indicate the true and false of the logic, to be and not. The descriptor for the Boolean type is "bool". The C + + standard does not specify the length of the Boolean type data, and the Boolean type in Visual C + + is 1 bytes. For example:

// Boolean variable bPass, indicating whether the exam passed
// Assign a value of true to indicate that the exam passed
bool bPass = true;
Unlike numerical data such as int, which is mainly used for calculations, boolean data is mainly used to save the results of logical judgments, or used in conditional structures or loop structures (described in detail in Chapter 4 later). Control the execution process. E.g:

cout << "Please enter your score:" << endl;
// an int variable that holds the input score
int nScore = 0;
// enter the score
cin >> nScore;
// Save the passed or failed bool type variable
// The default state is false, indicating that it failed
bool bPass = false;
// Use conditional structure for logical judgment
// determine if the input score is greater than or equal to 60
if (nScore> = 60)
{
    // Save the result of logical judgment
    // If the input score is greater than or equal to 60, the assignment is true,
   // means the exam passed, otherwise it will keep its initial value of false, which means it failed
   bPass = true;
}

// In the conditional structure, depending on the value of bPass,
// Control the execution path of the program
if (bPass)
{
   // If bPass is true, the output test passes
   cout << "Congratulations, you passed the exam" << endl;
}
else
{
   // If bPass is false, the output test fails
   cout << "Sorry, you did not pass the exam" << endl;
}
In this code, the bool type variable bPass is first used to save the result of the logical judgment, and records the result of the logical judgment whether the input score nScore is greater than or equal to 60. If nScore is greater than or equal to 60, bPass is assigned a value of true, otherwise, it retains its initial value of false, indicating that nScore is not greater than or equal to 60. In this way, the bool variable of type bPass holds the result of the logical judgment of "whether nScore is greater than or equal to 60".

Use bool type variables to save the results of logical judgments, not only for saving, but also for controlling the program's execution flow in conditions or loop structures. In the following if condition structure, bPass is used as the basis for condition judgment. If the value of bPass is true, a prompt is passed to pass the test; otherwise, a prompt is passed to fail the test. In this way, depending on the value of the bool type variable bPass, our program has different execution paths.

Best practice: Avoid implicit conversions of bool types and integers

Although the bool type variable has only two logical values, true and false, when it is used in a place that requires a numerical arithmetic value, the value of the bool type variable is implicitly converted to an integer value. If the value of a bool variable is false, the value participating in the operation after conversion is 0; otherwise, it is 1. Conversely, if we assign a numerical value (integer or decimal) to a variable of type bool, an implicit conversion from numeric data to a value of type bool will also occur. The value 0 is converted to false, and any other non-zero value is converted to true. E.g:

bool a = 4; // 4 is converted to true, the value of a is true
int b = a; // a is converted to 1, b is 1
int c = a + b; // a is converted to 1 to participate in the operation, and the value of c is 2
This conversion happens so secretly that some compilers don't even give warning messages. And once the code's behavior is very hidden, it means that there are likely to be hidden errors that are not easy to detect. Therefore, we should try to avoid using bool-type variables to assign values, or use bool-type variables for arithmetic operations, to prevent this kind of "sneaky" small actions.

3.5 Character and string types
"What's your license plate number?"

"Shaan A-82103"

We know that programming languages are essentially used to abstract, describe, and express the real world. In the face of various numerical data in the real world (for example, 216 for bus routes and 3.5 yuan per pound for tomato prices), we can define variables (int nNo, float fPrice) with the numerical data types introduced earlier. To abstract and express. In addition, there is another type of data in the real world-text data. For example, the license plate number "Shaan A-82103" in the above example is a text data. In order to express this type of text data, C ++ provides two data types, character type and string type, which are used to abstract and express text data. Among them, the character type is used to express a single character, such as 'A', '0', etc., and a string formed by combining multiple strings, we use the string type to express.

3.5.1 Character Type
When learning English, we always start with ABC single letters, and then we can connect them together to form a complete sentence. And if you want to express a more complex text data with a string in C ++, we also have to start from the individual characters that make up the string. In C ++, we use character types to abstract and express a single common character, whose type specifier is "char". E.g:

// Define the character type variable cA and assign it with the character constant ‘A’
char cA = ‘A’; // The cA variable represents the uppercase alphabetic character ‘A’
char cB;
cB = ‘-’; // cB variable represents the symbol character ‘-’
// output character 'A'
cout << cA << endl;
Although a variable of character type always appears as a character (assignment and output), in essence, it can be regarded as an integer data type that takes up less memory space and has a smaller value range. It only takes 1 byte of memory space, and the corresponding value range is also reduced to -128 ~ 127. When we need to express a small integer, in order to save memory resources, we can use the char type to express. Like integer data types, character types can be modified by the signed / unsigned keywords to form signed / unsigned character types. Therefore, char types can also participate in arithmetic operations. E.g:

// Assign the ASCII value corresponding to the capital letter character 'A' to the character type variable c
// equivalent to char c = ‘A’;
char c = 65;
// The variable t represents the invisible control character '\ t', which means outputting a Tab control
char t = ‘\ t’;
// loop output 26 uppercase alphabetic characters
for (int i = 0; i <26; ++ i)
{
    // print the character represented by c
    cout << c << t;

    // add 1 to the character type variable to make it the next character in the ASCII table
    c = c + 1;
}
Know more: Chinese characters with wchar_t

Because the char character type has a limited range of values, it can only be used to represent characters in a limited ANSCII character table, including common alphabetic characters and control characters. And if you want to represent a larger range of characters, such as the Chinese character 'shan' in the above example, char would be too much. In order to make up for the lack of char types, C ++ provides another character data type wchar_t, which takes up 2 bytes of memory space and has a wider range of values, so it can represent a wider range of characters, including Chinese characters, of course. For example, you can output a Chinese character in the following way. However, it should be noted here that because our code has extended Chinese characters, it is required that our code file be saved in UTF-8 encoding format.

// define a wchar_t type character variable
// and assign a value to it with a Chinese character
wchar_t cChs = L‘ Zeng ’;
// Set the area of wcout output object and output Chinese characters
wcout.imbue (locale ("chs"));
wcout << cChs << endl;
It is worth reminding here that the L prefix in front of character constants or string constants means that the characters or strings here are encoded using the wide-character character set (wide character set, usually the UNICODE character set). If the L prefix is not used, it means that it is encoded using the multibyte-character character set (multibyte character set). Therefore, if we want to initialize or assign a wide character (wchar_t) or wide string (wstring) variable with a character or string constant, we should prefix the character or string constant with an L. Conversely, if you initialize or assign variables of type char and string, you do not need to add the L prefix.

 

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

(Reprinted) Hello, C ++ (10) Have you passed this C ++ exam? Boolean data type for logical judgment in C ++

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.