所以我有一个问题,我已经有很长时间了,使用else if和链式if语句之间有什么区别,它们不会产生相同的东西吗?例如,以以下基本示例为例:
short age {0};
std::cin >> age;
if(age > 18) cout << "You are an adult";
if(age < 18) cout << "YOu are a teen";
if(age == 0) cout << "YOu are born";
和
short age {0};
std::cin >> age;
if(age > 18) cout << "You are an adult";
else if(age < 18) cout << "YOu are a teen";
else if(age == 0) cout << "YOu are born";
它们有何不同?
在您的特定示例中,它们是相同的(注意:问题已编辑;现在不一样了)。无论如何,请考虑以下内容:
if (age > 18) age = 17; // executes
if (age < 18) ... // executes!
现在您可以看到它的行为与
age = 19;
if (age > 18) age = 17; // executes
else if (age < 18) ... // skipped!
或正如@cubic所提到的,如果条件重叠,也将有所不同。
age = 20;
if (age > 19) ...; // executes
if (age > 17) ...; // executes!
与:
age = 20;
if (age > 19) ...; // executes
else if (age > 17) ...; // skipped!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句