嵌套的IF语句与IF-ELSE
我正在学习C语言usnig Turbo C ++编译器,并且我及时遇到了两个语句:
- IF(与许多IF嵌套)
- IF-else(不嵌套但继续其他,否则等等)
我想知道我的想法是否正确IF(与许多IF嵌套)和IF-else(非嵌套)是否相同? 建议非常感谢。
这只是背后的基本逻辑:
if
条件嵌套 :如果第一个条件的值为真,则进入第二个条件。
if(a > 0) { printf("A is greater than 0\n"); if(a > 2) printf("A is greater than 0 and 2\n"); }
if-else
条件 :如果第一个条件的值为false,则转到下一个:
if(a > 0) printf("A is greater than zero\n"); else if(a < 0) printf("A is lesser than zero\n"); else printf("A is zero\n");
还有一条你应该知道的指令 , switch
:
switch(a) { case 0: printf("A is zero\n"); break; case 1: printf("A is one\n"); break; case 5: printf("A is five\n"); break; default: printf("A is not 0, 1 or 5\n"); break; }
嵌套if
不等于if-else
。 if
具有组合条件,它可以等效于单个,例如:
if (a == 1) { if (b == 2) { ... } }
相当于:
if (a == 1 && b == 2) { ... }
我猜你的意思是:
if(expression){ //code } else{ if(expression){ //code } }
相当于:
if(expression){ //code } else if(expression){ //code }
是的,它完全一样。 第二个是更好看的方式。
else if
实际上嵌套了else
,因为C和C ++没有对“elseif”或“elif”概念的任何特殊支持(现在不谈论预处理器指令)。 严格使用块和缩进很明显:
if(something) { doSomething(); } else { if(anotherThing) { doAnotherThing(); } else { if(yetAnotherThing) { doYetAnotherThing(); } else { doSomethingElse(); } } }
使用通常的else if
代码编写的相同代码:
if(something) { doSomething(); } else if(anotherThing) { doAnotherThing(); } else if(yetAnotherThing) { doYetAnotherThing(); } else { doSomethingElse(); }
正如MateuszKwaśniak所提到的, else if
可能的else if
,你应该更喜欢switch
。 但是,特别是字符串比较是不可能的。