来讲讲switch语句:
switch是用来进行多分支选择的语句,一般结构是:
switch(变量表达式)
{
case xx1:
// ...
break;
case xx2
// ...
break;
default:
// ...
}
#include<stdio.h> #include<stdlib.h> int main() { int x = 3; int y = 3; switch (x % 2) { case 1: switch (y) { case 0: printf("first"); case 1: printf("second"); break; default: printf("hello"); } case 2: printf("third"); } system("pause"); return 0; }
结果为 hellothird
switch语句时多分支的选择语句,switch中表达式结果命中那个case,就执行该case子项,如果case子项后没有跟break语句,则继续往下执行。
补充
switch语句中的defaut子句可以放到任意位置
switch语句中case后的表达式只能是个常量
switch语句中case表达式不要求顺序
switch(x) x可以是什么类型
x只能是:整形和枚举类型,例如:int long char
不能是浮点型 float
static的特性
1. static修饰变量
a. 函数中局部变量:
声明周期延长:该变量不随函数结束而结束
初始化:只在第一次调用该函数时进行初始化
记忆性:后序调用时,该变量使用前一次函数调用完成之后保存的值
存储位置:不会存储在栈上,放在数据段
#include<stdio.h> #include<stdlib.h> int sum(int a) { int c = 0; static int b = 3; c += 1; b += 2; return (a + b + c); } int main() { int i; int a = 2; for (i = 0; i < 5; i++) { printf("%d,", sum(a)); } system("pause"); return 0; }
结果是 8,10,12,14,16
第一次循环:a=2 b=5 c=1 a+b+c=8
第二次循环:a=2 b=7 c=1 a+b+c=10
第二次循环:a=2 b=9 c=1 a+b+c=12
第二次循环:a=2 b=11 c=1 a+b+c=14
第二次循环:a=2 b=13 c=1 a+b+c=16
b. 全局变量
改变该变量的链接属性,让该变量具有文件作用域,即只能在当前文件中使用
假如有两个文件同时定义一个a,且初始化,则程序无法执行,
给其中一个int a前加static,使这个a只能在这个文件内执行,程序就能运行
c. 修饰变量时,没有被初始化时会被自动初始化为0
2. static修饰函数
改变该函数的链接属性,让该函数具有文件作用域,即只能在当前文件中使用
补充
const修饰变量为常量

编译器直接报错
arr已经成为常量不能被修改

浙公网安备 33010602011771号