C语言的程序控制(if 和 switch)

本文深入探讨了C语言中的if语句、if-else语句、嵌套if-else、条件操作符、switch语句的使用及注意事项,通过实例解析常见错误与最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

if语句
if(condition)
{
    ..../*语句*/
}

int x;
if(x)相当于 if(x != 0 )
if(!x)相当于 if(x == 0 )

一般错误
int x = -3;
if(x > 0);
    printf("Yes\n");

事实上,不管x 是否大于0,总是要打印Yes
错误在于在if语句后面使用;

int x = -10;
if(x = -20)
    printf("Yes\n");

if语句中的应该是一个判断,而不是一个赋值。判断的返回值是0或者1,赋值只要不等于0,那么返回值就是1,所以会打印Yes

有一个比较好的书写方式:
if(-20 == x) /* Instead of if(x == -20) */
这样就可以很好的避免写出等式

if( -20 = x) 这得到编译都无法通过的错误

#include <stdio.h>
int main(void)
{
	int i = 30;
  	if(i =! 20) /* Instead of != */
    	printf("One\n");
  	else
    	printf("Two\n");
    	printf("%d\n", i);
return 0;
}

!= 是不等于的意思,x=!20 是 x = (!20) , x = 0, x=!20的返回值时0,所以最后的输出是:
Two

if-else语句
if(condition)
{
... /* block of statements A */
}
else
{
... /* block of statements B */
}
嵌套if-else

if-else嵌套的原则就是,else属于离它最近的if语句:

#include <stdio.h>
int main(void)
{
	int a = 5;
	if(a != 5)
  	if(a-2 > 5)
    	printf("One\n");
	else
		printf("Two\n");
		
return 0;
}

因此,返回值是0.

强烈推荐使用{},下面的语句就更明确:

#include <stdio.h>
int main(void)
{
	int a = 5;
	
		if(a != 5){
  			if(a-2 > 5)
    			printf("One\n");
		}
		else
  			printf("Two\n");
return 0;
}

结果为: Two

?:条件操作符

exp1 ? exp2: exp3 ;
等价于:

if(exp1){
    exp2
}else}{
    exp3
}

赋值:

  int a = 5, k;
  k = (a > 0) ? 100 : -1;

k = 100

多个:?语句

k = exp1 ? exp2 : add1 ? add2 : add3;
if(exp1){
    k = exp2;
}
else if(add1){
    k = add2;
}
else{
    k = add3;
}
switch语句

switch语句是if-else-if替代语句。

switch(expression)
{
case constant_1:
    /* block of statements that will be executed if the value of the
    expression is equal to constant_1. */
    break;
case constant_2:
    /* block of statements that will be executed if the value of the
    expression is equal to constant_2. */
break;
...
    case constant_n:
    /* block of statements that will be executed if the value of the
    expression is equal to constant_n. */
    break;
default:
    /* block of statements that will be executed if the value of the
    expression is other than the previous constants. */
    break;
}

这个表达式的结果必须是一个整数,如果所有的条件都不满足的时候,那么就使用default这分支。

表达式中需要注意的是,我们的default这个关键字,必须写正确。
C语言中并不去判断你是否写正确,下面的程序中,我们也得不到任何错误提示

#include <stdio.h>
int main(void)
{
  int a;
  printf("Please input a number: ");
  scanf("%d",&a);

  switch(a){

    case 1:
      printf("The a vaule is %d\n",a);
      break;
    case 2:
      printf("The a vaule is %d\n",a);
      break;
    defaul:
      printf("The a vaule is %d\n",a);
  }
}

另外,break也是必不可少的关键字,如果不写的话,那么程序还是会继续运行,直到遇到break或者程序结束。

swtich与if对比

switch的条件往往受限于一个整型数,而if应用相对广泛。
switch相对if-else-if更直观,方便阅读,switch常常用来菜单设计上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值