五、 运算号、表达式和语句
3. 其他运算符
3.4 递减运算符:–
#include <stdio.h>
#define MAX 100
int main(void)
{
int count = MAX + 1;
while (--count > 0){
printf("%d bottles of spring water on the wall,"
"%d bottles of spring water!\n", count, count);
printf("Take one down and pass it around,\n");
printf("%d bottles of spring water!\n", count - 1);
}
return 0;
}
//100 bottles of spring water on the wall,100 bottles of spring water!
//Take one down and pass it around,
//99 bottles of spring water!
//99 bottles of spring water on the wall,99 bottles of spring water!
//Take one down and pass it around,
//98 bottles of spring water!
//...
//1 bottles of spring water on the wall,1 bottles of spring water!
//Take one down and pass it around,
//0 bottles of spring water!
3.5 优先级
y = 2;
n = 3;
nextnum = (y + n++)*6;
nextnum = (2 + 3)*6 = 5*6 =30
3.6 不要自作聪明
while (num < 21)
{
printf("%10d %10d\n", num, num*num++);
}
4 . 表达式和语句
4.1 表达式
4
-6
4+21
a*(b+ c/d)/20
q = 5*2
x = ++q %3
q > 3
■每个表达式都有一个值
表达式 | 值 |
---|---|
-4 + 6 | 2 |
c = 3 + 8 | 11 |
5 > 3 | 1 |
6 + (c = 3 + 8) | 17 |
4.2 语句
/* addemup.c -- 几种常见的语句 */
#include <stdio.h>
int main(void) /* 计算前20个整数的和 */
{
int count, sum; /* 声明 */
count = 0; /* 表达式语句 */
sum = 0; /* 表达式语句 */
while (count++ < 20) /* 迭代语句 */
sum = sum + count;
printf("sum = %d\n", sum); /* 表达式语句 */
return 0; /* 跳转语句 */
}
■副作用和序列点
4.3 复合语句(块)
/* 程序段 1 */
index = 0;
while (index++ < 10)
sam = 10 * index +2
printf("sam = %d\n", sam);
/* 程序段 2 */
index = 0;
while (index++ < 10)
{
sam = 10 * index +2
printf("sam = %d\n", sam);
}