C++ return:使函数立即结束

  • 内容
  • 评论
  • 相关

当函数中的最后一个语句已经完成执行时,该函数终止,程序返回到调用它的模块,并继续执行该函数调用语句之后的其他语句。但是,也有可能强制一个函数在其最后一个语句执行前返回到被调用的位置,这可以通过 return 语句完成。

如下面程序所示,在这个程序中,函数 divide 显示了 arg1 除以 arg2 的商。但是,如果 arg2 被设置为零,则函数返回到 main 而不执行除法计算。

#include <iostream>
using namespace std;

//Function prototype
void divide(double arg1, double arg2);

int main()
{
    double num1, num2;
    cout << "Enter two numbers and I will divide the first\n";
    cout << "number by the second number: ";
    cin >> num1 >> num2;
    divide(num1, num2);
    return 0;
}

void divide(double arg1, double arg2)
{
    if (arg2 == 0.0)
    {
        cout << "Sorry, I cannot divide by zero. \n" ;
        return;
    }
    cout << "The quotient is " << (arg1 / arg2) << endl;
}

程序输出结果:

Enter two numbers and I will divide the first
number by the second number: 12 0
Sorry, I cannot divide by zero.

程序中,用户输入了 12 和 0 这 2 个数字,它们被存储为变量 num1 和 num2 的双精度值。在第 13 行中,divide 函数被调用,将 12.0 传入 arg1 形参,并将 0.0 传入 arg2 形参。在 divide 函数中,第 19 行的 if 语句执行,因为 arg2 等于 0.0,所以第 21 行和第 22 行中的代码执行。当第 22 行中的 return 语句执行时,divide 函数立即结束,这意味着第 24 行中的 cout 语句不执行。程序继续执行 main 函数中的第 14 行。

本文标题:C++ return:使函数立即结束

本文地址:https://www.hosteonscn.com/3737.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注