if语句是条件判断语句,if语句的语法与while相似
if (test-condition)
statement
即:如果测试条件(test-condition)为true,则执行statement语句
这里的statement语句既可以是一条语句,也可以使多条语句组成的语句块。
但是这里必须注意:如果是多条语句,必须用大括号括起来。
否则就只会执行if语句下紧跟着的一句,而不会执行多余的语句。
当然为了养成良好的编码习惯,我们经常要求即使if下面只有条语句,我们也要使用大括号括起来。
if语句的几种常见的用法:
1. if语句单独使用
2. if ... else配合使用
3. if ... else if ... else配合使用
源码:
// Len_ifelse.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
char data[5] = { "abcd" };
// 1. if单独使用
printf("\n\n1. if单独使用\n");
for (int t = 0; t < strlen(data); t++)
{
if (data[t] == 'c')
{
printf("\t I find the c\n");
}
}
// 2. if...else配合使用
printf("\n\n2. if...else配合使用\n");
for (int t = 0; t < strlen(data); t++)
{
if (data[t] == 'c')
{
printf("\t I find the c\n");
}
else
{
printf("\t The data is:%c\n", data[t]);
}
}
// 3. if...else if... else配合使用
printf("\n\n3. if...else if...else配合用\n");
for (int t = 0; t < strlen(data); t++)
{
if (data[t] == 'c')
{
printf("\t I find the c\n");
}
else if (data[t] == 'a')
{
printf("\t I find the a\n");
}
else
{
printf("\t The data is:%c\n", data[t]);
}
}
return 0;
}
执行结果: