乱读天书, 不求甚解
周祎骏的个人云笔记
Toggle navigation
乱读天书, 不求甚解
主页
Linux:系统配置
Linux:用户管理
Linux:优化排错
Linux:进程调度
Linux:文件系统
Linux:网络
Linux:系统服务
Linux:安全
Linux:内核
容器:Docker
容器:containerd
容器编排:Kubernetes
IAC:Terraform
大数据:Hadoop
大数据:Zookeeper
大数据:Hbase
消息队列:rsyslog
消息队列:kafka
数据库:MySQL
数据库:MongoDB
搜索引擎:Elasticsearch
时序数据库:OpenTSDB
网站服务:Nginx
编程:Bash
编程:Perl
编程:Python
编程:C
编程:JAVA
编程:Rust
版本控制:gitlab
知识管理:docusaurus
常用小工具
关于我
标签
C 0.2 控制流
2018-06-17 08:23:04
64
0
0
admin
> if,for,while,switch,goto ... **break**立刻退出当前循环 **continue**立刻进行下一次循环 #if ```c #include <stdio.h> main() { int n=1; if (n==2) { printf("yes\n");} else if (n==0) { printf("0\n");} else { printf("no\n");} } ``` > if后的表达式非0为真,0为假 *** #三元表达式 ``` expr1 ? expr2 : expr3 ``` >如果expr2 与expr3 返回类型不同,会被强制转换。比如expr2是int ,expr3 是float, 那么无论expr1为真还是假,这个表达式的返回值都会被转换成float。 *** #for ```c #include <stdio.h> main() { int n; for (n=0;n<=10;n=n+1) { printf("%d\n",n); } ``` **逗号运算符常用于for语句中,它从左往右运行,最右侧表达式的类型和值即该逗号表达式的类型和值** ``` #include <stdio.h> main() { if (0,0,3) printf("true because of 3\n"); int x,y; for(x=0,y=0;x<3,y<5;x++,y++) printf("x=%d,y=%d\n",x,y); //最终会在x=4,y=4结束 } ``` *** #while ```c #include <stdio.h> main() { int n = 0; while (n<=5) { printf("%d\n",n); n=n+1; } } ``` *** #do-while 先跑语句再判断,也就是说无论如何会跑一遍 ``` #include <stdio.h> main() { int n=0; do { printf("%d\n",n); n=n+1; } while (n<0);//还是会运行一次,打出0 } ``` *** #switch ``` #include <stdio.h> main() { switch (0){ //switch 从满足条件的那一条开始往下依次运行 *所有* 的语句 case 0: case 1: case 2: //0,1,2三种情况都会运行 printf("<3\n"); break; //强制退出switch,避免后面的语句被运行 case 3: printf(">3\n"); break; case 4: case 5: printf(">3 <5\n"); break; default://所有条件都不满足的时候运行,非必要 printf(">5\n"); break; //switch语句后面加break 是好习惯。 } } ``` **小细节**: 以下代码会报错 error: a label can only be part of a statement and a declaration is not a statement ``` switch(0){ case 0: int a = 0; } ``` 因为case XXX其实就是一个类似goto XXX的label,后面需要跟一个执行语句,而声明变量不属于执行语句 改成以下的样子就可以运行了 ``` switch(0){ case 0: { int a = 0; } } ``` *** #goto 多数情况下会影响易读性,建议不要滥用 ``` #include <stdio.h> main() { printf("1\n"); printf("2\n"); goto label1; printf("3\n"); printf("4\n"); label1: printf("5\n"); printf("6\n"); } ```
上一篇:
C 0.12 寄存器变量
下一篇:
C 0.3 函数
文档导航