4-10 if语句介绍

假设你要去市场采购,室友对你说:“如果草莓在打折,就买些回来。”这便是条件语句——只有当条件(‘草莓在打折’)成立时,才会执行相应动作(“买些回来”)。

此类条件在编程中极为常见,它使我们能够在程序中实现条件行为。C++中最简单的条件语句称为if语句if statement。if语句允许我们在某个条件成立时执行一行(或多行)代码。

最简单的if语句采用以下形式:

if (condition) true_statement;

为提高可读性,通常采用以下写法:

if (condition)
    true_statement;

条件condition(也称为条件表达式conditional expression)是一种评估为布尔值的表达式。

如果if语句的条件评估为布尔值true,则执行true_statement;如果条件评估为布尔值false,则跳过true_statement。


使用if语句的示例程序

给定以下程序:

#include <iostream>

int main()
{
    std::cout << "Enter an integer: ";
    int x {};
    std::cin >> x;

    if (x == 0)
        std::cout << "The value is zero\n";

    return 0;
}

以下是该程序运行一次的输出结果:

image

让我们更详细地分析其工作原理。

首先,用户输入一个整数。随后评估条件 x == 0。等号运算符 (==) 用于检测两个值是否相等。当操作数相等时,运算符 == 返回 true;否则返回 false。由于 x 的值为 0,且 0 == 0 为真,因此该表达式评估结果为 true。

由于条件评估为真,后续语句执行,输出“The value is zero”。

下面是该程序的另一轮运行:

image

在此情况下,x == 0 的表达式结果为 false。后续语句将被跳过,程序终止,且不会再输出任何内容。

警告
if 语句仅能条件性地执行单个语句。关于如何条件性地执行多个语句,我们将在第 8.2 课——if 语句与代码块中进行讲解。


if-else

根据上述示例,如果我们想告知用户输入的数字非零该怎么办?

我们可以这样编写代码:

#include <iostream>

int main()
{
    std::cout << "Enter an integer: ";
    int x {};
    std::cin >> x;

    if (x == 0)
        std::cout << "The value is zero\n";
    if (x != 0)
        std::cout << "The value is non-zero\n";

    return 0;
}

或者这样:

#include <iostream>

int main()
{
    std::cout << "Enter an integer: ";
    int x {};
    std::cin >> x;

    bool zero { (x == 0) };
    if (zero)
        std::cout << "The value is zero\n";
    if (!zero)
        std::cout << "The value is non-zero\n";

    return 0;
}

这两个程序都比实际需要的更复杂。相反,我们可以使用if语句的另一种形式——if-else。if-else的结构如下:

if (condition)
    true_statement;
else
    false_statement;

如果条件评估为布尔值 true,则执行 true_statement。否则执行 false_statement。
让我们修改之前的程序,使用 if-else 语句。

#include <iostream>

int main()
{
    std::cout << "Enter an integer: ";
    int x {};
    std::cin >> x;

    if (x == 0)
        std::cout << "The value is zero\n";
    else
        std::cout << "The value is non-zero\n";

    return 0;
}

现在我们的程序将产生以下输出:

image

image


链式if语句

有时我们需要依次检查多个条件的真伪。可通过将if语句(或if-else语句)与前置if-else语句进行链式连接实现,如下所示:

#include <iostream>

int main()
{
    std::cout << "Enter an integer: ";
    int x {};
    std::cin >> x;

    if (x > 0)
        std::cout << "The value is positive\n";
    else if (x < 0)
        std::cout << "The value is negative\n";
    else
        std::cout << "The value is zero\n";

    return 0;
}

小于运算符(<)用于测试一个值是否小于另一个值。同样地,大于运算符(>)用于测试一个值是否大于另一个值。这两个运算符均返回布尔值。

以下是该程序多次运行的输出结果:

image

image

image

请注意,你可以根据需要评估的条件数量,无限次地串联if语句。在测验中我们将看到一个展示这种用法价值的示例。


布尔返回值与if语句

在上节课(4.9——布尔值)中,我们编写了这样一个使用返回布尔值函数的程序:

#include <iostream>

// returns true if x and y are equal, false otherwise
bool isEqual(int x, int y)
{
    return x == y; // operator== returns true if x equals y, and false otherwise
}

int main()
{
    std::cout << "Enter an integer: ";
    int x {};
    std::cin >> x;

    std::cout << "Enter another integer: ";
    int y {};
    std::cin >> y;

    std::cout << std::boolalpha; // print bools as true or false

    std::cout << x << " and " << y << " are equal? ";
    std::cout << isEqual(x, y); // will return true or false

    std::cout << '\n';

    return 0;
}

让我们使用if语句改进这个程序:

#include <iostream>

// returns true if x and y are equal, false otherwise
bool isEqual(int x, int y)
{
    return x == y; // operator== returns true if x equals y, and false otherwise
}

int main()
{
    std::cout << "Enter an integer: ";
    int x {};
    std::cin >> x;

    std::cout << "Enter another integer: ";
    int y {};
    std::cin >> y;

    if (isEqual(x, y))
        std::cout << x << " and " << y << " are equal\n";
    else
        std::cout << x << " and " << y << " are not equal\n";

    return 0;
}

该程序的两轮运行:

image

image

在此情况下,我们的条件表达式仅是对 isEqual 函数的调用,该函数返回一个布尔值。


非布尔条件语句

在上述所有示例中,我们的条件语句要么是布尔值(true 或 false),要么是布尔变量,要么是返回布尔值的函数。那么当条件表达式无法评估为布尔值时会发生什么?

此时条件表达式的结果将被转换为布尔值:非零值转换为布尔真,零值转换为布尔假。

因此,若我们执行如下操作:

#include <iostream>

int main()
{
    int x { 4 };
    if (x) // nonsensical, but for the sake of example...
        std::cout << "hi\n";
    else
        std::cout << "bye\n";

    return 0;
}

这将输出 hi,因为 x 的值为 4,而 4 是非零值,会被转换为布尔值 true,导致条件语句后的语句执行。

关键要点
if (x) 表示“如果 x 不为零/非空”。


if语句与提前返回

若函数中的return语句并非最后一条语句,则称为提前返回。此类语句将在执行时使函数返回调用方(早于函数正常返回的时间点,故称“提前”)。

无条件提前返回并无实际意义:

void print()
{
    std::cout << "A" << '\n';

    return; // the function will always return to the caller here

    std::cout << "B" << '\n'; // this will never be printed
}

由于 std::cout << “B” << ‘\n’; 永远不会被执行,我们不妨将其移除,这样我们的返回语句就不再属于提前返回。

然而,当与 if 语句结合使用时,提前返回为函数的返回值提供了条件化处理的方式。

#include <iostream>

// returns the absolute value of x
int abs(int x)
{
    if (x < 0)
        return -x; // early return (only when x < 0)

    return x;
}

int main()
{
    std::cout << abs(4) << '\n'; // prints 4
    std::cout << abs(-3) << '\n'; // prints 3

    return 0;
}

image

当调用 abs(4) 时,x 的值为 4。由于 (x < 0) 为假,因此提前返回语句不会执行。函数在结束时将 x(值为 4)返回给调用方。

当调用 abs(-3) 时,x 的值为 -3。if (x < 0) 为真,因此提前返回执行。此时函数将 -x(值 3)返回给调用方。

历史上,提前返回曾不被认可。但在现代编程中,这种做法已更被接受,尤其当它能简化函数结构,或用于因错误条件提前终止函数时。

相关内容
关于提前返回的讨论将在第8.11节——中断与继续中进一步展开。

我们将在后续的第8.2节——if语句与代码块中继续探索if语句的相关内容。


测验时间

问题 #1

什么是提前返回,其行为特征是什么?

显示解答

提前返回是指在函数最后一行之前出现的返回语句。它会导致函数立即返回给调用方。

问题 #2

质数是指大于1且只能被1和自身整除的整数。编写程序提示用户输入0至9(含)之间的数字。若输入的数字属于该范围且为质数(2、3、5或7),则输出“该数字是质数The digit is prime”;否则输出“该数字不是质数The digit is not prime”。

显示提示

提示:使用一系列if-else语句将用户输入的数字与质数进行比较,以判断是否存在匹配项。

显示解答

#include <iostream>

bool isPrime(int x)
{
    if (x == 2) // if user entered 2, the digit is prime
        return true;
    else if (x == 3) // if user entered 3, the digit is prime
        return true;
    else if (x == 5) // if user entered 5, the digit is prime
        return true;
    else if (x == 7) // if user entered 7, the digit is prime
        return true;

    return false; // if the user did not enter 2, 3, 5, 7, the digit must not be prime
}

int main()
{
    std::cout << "Enter a number 0 through 9: ";
    int x {};
    std::cin >> x;

    if ( isPrime(x) )
        std::cout << "The digit is prime\n";
    else
        std::cout << "The digit is not prime\n";

    return 0;
}

对于高级读者

如果上面isPrime()函数看起来有些冗长/重复——确实如此。我们可以用后续课程将要讲解的概念,更紧凑高效地重写isPrime()函数。

使用逻辑或运算符(||)(6.8节——逻辑运算符):

bool isPrime(int x)
{
    return x == 2 || x == 3 || x == 5 || x == 7; // if user entered 2 or 3 or 5 or 7 the digit is prime
}

使用 switch 语句(8.5 -- switch 语句基础):

bool isPrime(int x)
{
    switch (x)
    {
        case 2: // if the user entered 2
        case 3: // or if the user entered 3
        case 5: // or if the user entered 5
        case 7: // or if the user entered 7
            return true; // then the digit is prime
    }

    return false; // otherwise the digit must not be prime
}

问题 #3

如何缩短以下代码的长度(不改变格式)?

#include <iostream>

bool isAllowedToTakeFunRide()
{
  std::cout << "How tall are you? (cm)\n";

  double height{};
  std::cin >> height;

  if (height >= 140.0)
    return true;
  else
    return false;
}

int main()
{
  if (isAllowedToTakeFunRide())
    std::cout << "Have fun!\n";
  else
    std::cout << "Sorry, you're too short.\n";

  return 0;
}

显示答案

在 isAllowedToTakeFunRide() 中无需使用 if 语句。表达式 height >= 140.0 的评估结果为布尔值,可直接返回。

bool isAllowedToTakeFunRide()
{
  std::cout << "How tall are you? (cm)\n";

  double height{};
  std::cin >> height;

  return height >= 140.0;
}

你永远不需要以下形式的if语句:

if (condition)
  return true;
else
  return false;

这可以被单条语句的返回条件所替代。

posted @ 2026-02-14 10:00  游翔  阅读(0)  评论(0)    收藏  举报