1.case的穿透问题
- switch里面的case只要匹配一次其它的都失效,包括default. 正是因为switch的这个特性, 所以可能导致程序出现逻辑错误
- 为了避免上述情况,C语言还提供了一种break语句,专用于跳出switch语句,break语句只有关键字break,没有参数。
2.default的位置问题
- default可以省略
- default语句可以写在switch语句中的任意位置
3.goto
- goto语句是无条件转移语句,其一般格式如下: goto 语句标号;
- 其中语句标号是按标识符规定书写的符号, 放在某一语句行的前面,标号后加冒号。语句标号起标识语句的作用,与goto 语句配合使用。
#include <stdio.h> void main() { int i=0; if(i==0) goto end; for(i=0; i<10; i++) printf("%d ", i); end: printf("the end "); }
示例代码:你猜我猜
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
//1.定义变量存储用户输入
int i = 0, age;
//2.产生一个0~25之间的随机数
int computer = arc4random_uniform(25);
//3.设置三次循环
while (i < 3) {
i++;
printf("第%i次猜年龄
", i);
scanf("%i", &age);
if (age < computer) {
printf("猜小了,再猜一次
");
}else if(age > computer){
printf("我有那么老吗?
");
}else if (age == computer) {
printf("猜对了,咱们约会吧!
");
//猜对了直接跳转
// goto out;
return 0;
}
}
//4.如果三次都猜错,输出下一行
printf("真是笨,三次都没猜对!
");
// out:
return 0;
}
4.for循环
- 表达式省略(三个表达式都可以省略)
- 如:for(; ;) 语句相当于while(1) 语句,即不设初值,不判断条件(认为表达式2为真值),循环 变量不增值。无终止地执行循环体。
- if else省略大括号,else往上找最近的if匹配;
- 获取当前系统时间
#include <time.h> int main(int argc, const char * argv[]) { //获取当前系统时间 time_t timer; struct tm *p; timer = time(NULL); p = localtime(&timer); printf("当前时间是: %s ",asctime(p)); return 0; }