详解C++编程中的条件判断语句if-else与switch的用法
if-else 语句 if ( expression ) statement1 [else statement2] 备注 // if_else_statement.cpp #include <stdio.h> int main() { int x = 0; if (x == 0) { printf_s("x is 0!n"); } else { printf_s("x is not 0!n"); // this statement will not be executed } x = 1; if (x == 0) { printf_s("x is 0!n"); // this statement will not be executed } else { printf_s("x is not 0!n"); } return 0; } 输出: x 是 0! x 不是 0! switch 语句 switch ( expression ) case constant-expression : statement [default : statement] 备注
如果找到匹配的表达式,则后续 case 或 default 标签不会妨碍控制。 break 语句用于停止执行并将控制转移到 switch 语句之后的语句。如果没有 break 语句,则将执行从匹配的 case 标签到 switch 末尾的每个语句,包括 default。例如: // switch_statement1.cpp #include <stdio.h> int main() { char *buffer = "Any character stream"; int capa,lettera,nota; char c; capa = lettera = nota = 0; while ( c = *buffer++ ) // Walks buffer until NULL { switch ( c ) { case 'A': capa++; break; case 'a': lettera++; break; default: nota++; } } printf_s( "nUppercase a: %dnLowercase a: %dnTotal: %dn",capa,(capa + lettera + nota) ); } 在上面的示例中,如果 c 是大写 A,则 capa 将递增。 capa++ 之后的 break 语句会终止 switch 语句体的执行并将控制转移到 while 循环。如果没有 break 语句,lettera 和 nota 也将递增。 case 'a' 的 break 语句也能达到类似的目的。如果 c 是小写 a,则 lettera 将递增,并且 break 语句将终止 switch 语句体。如果 c 不是 a 或 A,则将执行 default 语句。 // switch_statement2.cpp // C2360 expected #include <iostream> using namespace std; int main(int argc,char *argv[]) { switch( tolower( *argv[1] ) ) { // Error. Unreachable declaration. char szChEntered[] = "Character entered was: "; case 'a' : { // Declaration of szChEntered OK. Local scope. char szChEntered[] = "Character entered was: "; cout << szChEntered << "an"; } break; case 'b' : // Value of szChEntered undefined. cout << szChEntered << "bn"; break; default: // Value of szChEntered undefined. cout << szChEntered << "neither a nor bn"; break; } } switch 语句可以嵌套。在这种情况下,case 或 default 标签将与封装它们的最近的 switch 语句关联。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |