《Beginning C++17》-学习笔记-Chapter 04-Making Decisions

本文深入探讨了C++中的布尔类型,包括true和false的使用,以及如何在代码中进行条件判断。通过示例讲解了逻辑运算符的短路评估特性,展示了如何使用if-else和switch-case语句来实现复杂逻辑分支,并介绍了C++17标准下变量声明的新语法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

There are only two possible bool values, true and false. True and false are keywords and are literals of type bool. They are
sometimes called Boolean literals.

#include <iostream>

int main()
{

	bool isValid{ true }; // Define and initialize a logical variable to true.

	bool isFalse{}; // Define and initialize a logical variable to false.

	std::cout << isValid << std::endl;//输出1
	std::cout << std::boolalpha;//This statement makes bool values output as true and false
	std::cout << isFalse << std::endl;//输出false
	std::cout << std::noboolalpha;// This statement returns output of bool values to the default setting, which is o or 1
	std::cout << (4<5) << std::endl;//输出1

}

If you cast true to an integer type, the result will be 1; casting false to an integer results in 0. Conversely, you can also convert numerical values to type bool. Zero converts to false, and any nonzero value converts to true. When you have a numerical value where a bool value is expected, the compiler will insert an implicit conversion to convert the numerical value to type bool.


#include <iostream>
#include <cctype>  /*functions in this header return values of type int. The value will be nonzero (true) if the character is of the type being tested for, and 0 (false) if it isn’t. The reason they don’t return a bool value is that they originate from the C Standard Library and predate type bool in C++.*/

int main()
{
	char letter{}; // Store input here
	std::cout << "Enter a letter: "; // Prompt for the input
	std::cin >> letter;

	if (std::isupper(letter))
	{
		std::cout << "You entered an uppercase letter." << std::endl;
		std::cout << "Convert it to uppercase as:" << static_cast<char>(std::tolower(letter));/* The result of function "tolower()" will be returned as type int, so you need to explicitly cast it if you want to store it as type char*/
		return 0;
	}

	else
	{
		std::cout << "You entered a lowercase letter." << std::endl;
		std::cout <<"Convert it to uppercase as:" << static_cast<char>(std::toupper(letter));
		return 0;
	}
}

An else always belongs to the nearest preceding if that’s not already spoken for by another else.

When an else block is another if, writing else if on one line is an accepted convention.


The binary logical operators are so-called short-circuit operators.

If the first operand to a binary logical expression already determines the outcome, the compiler will make sure no time is wasted evaluating the second operand. This property of the logical operators && and || is called short-circuit evaluation.

The second operand of && is evaluated only after the first operand evaluates to true, and the second operand of || only after the first evaluates to false.


// Using the conditional operator to select output.
#include  <iostream>

int main()
{
	int apple{};               // 苹果数量

	std::cout << "How many apple(s) do you have? ";
	std::cin >> apple;

	std::cout << "I have " << apple
		<< (((apple == 1 ) || (apple ==0))? " apple" : " apples")
		<< " in total." << std::endl;
}

You can only switch on values of integral (int, long, unsigned short, etc.), character (char, etc.), and enumeration types.

Each case value must be a constant expression, which is an expression that the compiler can evaluate at compile time.
 

// Using the switch statement
#include <iostream>
#include <cctype>		// for std::isalpha() and tolower()

int main()
{
	char letter{};
	std::cout << "Enter a letter: ";
	std::cin >> letter;

	if (std::isalpha(letter))//检查输入的字符是否是字母
	{
		switch (std::tolower(letter))
		{
		case 'a': 
			std::cout << "You entered vowel 'a'." << std::endl;
			[[fallthrough]];/*can add a [[fallthrough]] statement in the same place where you would otherwise add a break statement to prevent compiler to issue a warning when compiling your program. This feature is available from C++ 17.*/
		case 'e': case 'i': case 'o': case 'u':
			std::cout << "You entered a vowel." << std::endl;
			break;/*This statement will break out of the if-else and exit the program. A break statement is not the only way to move control out of a switch statement. If the code following a case label contains a return statement, control instantly exits not only the switch statement but the surrounding function as well. */
		default:
			std::cout << "You entered a consonant." << std::endl;
			break;
		}
	}
	else
	{
		std::cout << "You did not enter a letter." << std::endl;
	}
}

Selecting Language Standard
To enable the latest features of the C++ language outlined in this book it is necessary to manually change the language standard setting for your project. You can do this by first going to Project ➤ Properties to bring up the Property pages. From there, navigate to Configuration Properties ➤ C/C++ ➤ Language ➤ C++ Language Standard. Select the ISO C++17 standard from the drop-down list. Click OK and the project will now be configured to compile according to the C++17 language standard.

 


Any variable declared within a block ceases to exist at the end of the block, so you cannot reference it outside the block

In general, it is considered good coding style to limit the scope of variables to the region in which they are used.

#include <iostream>

int main()
{
	int input;
	std::cout << "Enter a number" << std::endl;
	std::cin >> input;
	if (int local_value{input}; local_value > 0) /*This is a new way, beginnig with C++ 17, of initializing a variable within the scope of an if-else.*/
	{
		std::cout << "value entered is larger than 0." << std::endl;
	}
	else
	{
		std::cout << "value entered is not larger than 0." << std::endl;

	}

}

 

/*Even though starting with C++14, C++ supports binary integral literals (of form 0b11001010), C++ standard output functions and streams do not support outputting integral values in binary format. They mostly do support hexadecimal and octal formatting—for std::cout, for instance, you can use the std::hex and std::oct output manipulators defined in <ios>. But to output a character in binary format, you’ll thus have to write some code yourself. A char normally has only eight bits, remember? You can just stream these bits one by one.*/

#include <iostream>

int main() {
	char ch{};
	std::cout << "Enter a letter: ";
	std::cin >> ch;

	// Output the character code as binary
	std::cout << "The binary code for '" << ch << "' is "
		<< ((ch & 0b10000000) ? 1 : 0)
		<< ((ch & 0b01000000) ? 1 : 0)
		<< ((ch & 0b00100000) ? 1 : 0)
		<< ((ch & 0b00010000) ? 1 : 0)
		<< ((ch & 0b00001000) ? 1 : 0)
		<< ((ch & 0b00000100) ? 1 : 0)
		<< ((ch & 0b00000010) ? 1 : 0)
		<< ((ch & 0b00000001) ? 1 : 0)
		<< std::endl;

	return 0;
}

 

Welcome to Beginning C++17. This is a revised and updated version of Ivor Horton’s original book called Beginning ANSI C++. The C++ language has been extended and improved considerably since then, so much so that it was no longer possible to squeeze detailed explanations of all of C++ into a single book. This tutorial will teach the essentials of the C++ language and Standard Library features, which will be more than enough for you to write your own C++ applications. With the knowledge from this book, you should have no difficulty in extending the depth and scope of your C++ expertise. We have assumed no prior programming knowledge. If you are keen to learn and have an aptitude for thinking logically, getting a grip on C++ will be easier than you might imagine. By developing C++ skills, you’ll be learning a language that is already used by millions and that provides the capability for application development in just about any context. C++ is very powerful. Arguably, it’s more powerful than most programming languages. So, yes, like with any powerful tool you can wield some considerable damage if you use it without proper training. We often compare C++ to a Swiss Army knife: age-old, trusted, incredibly versatile, yet potentially mind-boggling and full of pointy things that could really hurt you. Once someone clearly explains to you what all the different tools are meant for, however, and teaches you some elementary knife safety rules, then you’ll never have to look for another pocketknife again. C++ does not need to be dangerous or difficult at all either. C++ today is much more accessible than many people assume. The language has come a long way since its conception nearly 40 years ago. In essence, we have learned how to wield all its mighty blades and tools in the safest and most effective way possible. And, more importantly perhaps, the C++ language and its Standard Library have evolved accordingly to facilitate this. The past decade in particular has seen the ris
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值