如何在以下程序中将调用者的 NULL 指针作为三个参数中的任何一个发送到 CalcArea 函数?无论我如何修改 if () 语句的条件(不是内容),我仍然看到 cout << "why am I seeing this..."<
#include <iostream>
using namespace std;
void CalcArea(const double* const pPi,
const double* const pRadius,
double* const pArea)
{
if (pPi && pRadius && pArea)
*pArea = (*pPi) * (*pRadius) * (*pRadius);
cout<< "why am I seeing this?..." <<endl;
}
int main()
{
const double Pi = 3.1416;
cout<< "enter radius of circle: ";
double Radius = 0;
cin>> Radius;
double Area = 0;
CalcArea (&Pi, &Radius, &Area);
cout<< "area is = " <<Area<<endl;
cout<< "press enter to continue..." <<endl;
cin.ignore(10, '\n');
cin.get();
return 0;
}
请帮助我理解。它在我的书中说“如果调用者无意中将 NULL 指针作为三个参数中的任何一个发送,您不希望函数计算面积”,但是在什么条件下会发生这种情况呢? if() 语句要防止的条件是什么。记住我才刚刚开始。谢谢大家,真诚的,newmanadam
最佳答案
只有紧跟在 if 之后的行取决于评估。
if (condition)
statement
如果您希望两条线仅在条件成立时运行,请使用大括号。
if (condition)
{
multiple
statements
}
此处的 if 条件只是检查您提供给它的所有引用是否为空。如果您使用 NULL 显式调用您的函数,就会发生这种情况
CalcArea(&Pi, NULL, &Area);
或者,如果您使用的是先前已设置为空的指针。由于您是从书本中学习,我想它会很快向您解释。
关于c++ - if() 语句使用条件的目的是什么? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34444191/