例1:if判断语句
# include
int main(void)
{
int a = 5, b = 4, c = 3, d = 2;
if (a > b > c)
printf("%d\n", d);
else if ((c - 1 >= d) == 1)
printf("%d\n", d + 1);
else
printf("%d\n", d + 2);
return 0;
}
- 先执行a>b,为真,返回1,再比较1>c
- c-1大于等于d成立,返回1,判断1是否等于1
/*运行结果*/
3
Press any key to continue
例2:三目运算
# include
int main(void)
{
int a = 1, b = 2, c = 3, d = 4;
printf("%d\n", (a < b ? a : c < d ? a : d));
return 0;
}
- 先比较后一个三目运算,整体的值作为前一个三目运算的第二个值
- c
- a
/*运行结果*/
1
Press any key to continue
例3:两个数据交换
/*两个数据交换*/
# include
int main(void)
{
int a = 3, b = 5, t;
t = a;
a = b;
b = t;
a = a + b;
b = a - b;
a = a - b;
printf("a = :%d, b = %d", a, b);
return 0;
}
例4:do while循环
/*do while循环*/
# include
int main(void)
{
int n = 0, p;
do
{
scanf("%d", &p);
n++;
}while(p != 1234 && n < 3);
printf("p = %d, n = %d\n", p, n);
return 0;
}
- while后的条件语句因为是非等于,所以后面的且运算换成或运算,即
while(p = 1234 || n >= 3)
/*运行结果*/
123
12
123
p = 123, n = 3
Press any key to continue
例5:break
/*break*/
# include
int main(void)
{
int k = 5, n = 0;
while (k > 0)
{
switch (k)
{
default: //default的位置不会影响switch语句从哪进入
break; //跳出switch语句
case 1:
n += k;
case 2:
case 3:
n += k;
}
k--;
}
printf("n = %d\n", n);
return 0;
}
/*运行结果*/
n = 7
Press any key to continue
例5:break 和 continue
/*break & continue*/
# include
int main(void)
{
int a, b;
for(a = 1, b = 1; a <= 100; a++)
{
if(b >= 10)
break; //终止for循环
if(b % 3 == 1)
{
b += 3;
continue; //跳过本次循环,继续下次循环
}
}
printf("a = %d\n", a);
return 0;
}
/*运行结果*/
a = 4
Press any key to continue
例6:循环嵌套
/*循环嵌套*/
# include
int main(void)
{
int i, j, x = 0;
for(i = 0; i < 2; i++)
{
x++;
for(j = 0; j < 3; j++)
{
if(j % 2)
continue;
x++;
}
x++;
}
printf("x = %d\n", x);
return 0;
}
- 最内层的for循环执行的次数等于外层循环的次数乘以内层循环的次数
- 第一个for循环2次,第二个for循环3次,所以第二个for循环执行6次
x = 8
Press any key to continue
例7:字符串数组
/*字符串数组*/
# include
int main(void)
{
char str[][5] = {
"A","Bad","Boy!"};
char * p = &str[0][0];
printf("%s\n", p + 5);
return 0;
}
- str是一个5列的数组,p+5即指向的是B,向后输出Bad,遇到
\0
结束输出
/*运行结果*/
Bad
Press any key to continue
例8:变量的作用域
/*变量的作用域*/
# include
int main(void)
{
int a = 3, b = 5;
{
int a = 5;
b += a;
}
b *= a;
printf("b = %d\n", b);
return 0;
}
- 内部定义了与外部同名的变量a,内部使用内部定义的变量,外部则使用外部定义的变量
b = 30
Press any key to continue
例8:宏定义
/*宏定义*/
# include
# define Max(x, y) (x) >= (y) ? (x) : (y)
int main(void)
{
int i = 10, j = 15;
printf("%d", 10 * Max(i, j));
return 0;
}
- 输出的展开为:
10*(i) >= (j) ? (x) : (y)
即:10*10 >= 15 ? 10 : 15
- 所以最后即为:
100 >= 15 ? 10 : 15
,输出为10
/*运行结果*/
10
Press any key to continue
【文章源码参考GitHub】
以上内容均属原创,如有不详或错误,敬请指出。