当函数中的最后一个语句已经完成执行时,该函数终止,程序返回到调用它的模块,并继续执行该函数调用语句之后的其他语句。
但是,也有可能强制一个函数在其最后一个语句执行前返回到被调用的位置,这可以通过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;
}
程序输出结果: