Brian和Dennis的《c程序设计语言》(The C Programming Language)真不愧为c语言方面的经典书籍,薄薄的一本,却让人爱不释手,每次阅读都能有所收获。好记忆不如烂笔头,有些规则、算法还是记录下来比较好,记录下来常常回顾,才是提升编程内功的不二法门。
变量与表达式
1 整数除法操作将执行舍位。
2 浮点常量取的是整数,在书写时最好还是为它加上一个显示的小数点,这样可以强调其浮点信息,便于阅读。
3 在允许使用某种类型变量值的任何场合,都可以使用该类型的更复杂的表达式。
for语句
4 for语句比较适合初始化和增长步长都是单条语句并且逻辑相关的情形,因为它将循环控制语句集中放在一起,且比while语句更紧凑。
符号常量
5 #define指令可以把符号常量定义为一个特点的字符串:
#define 名字 替换文本
6 符号常量名通常用大写字母拼音,这样可以很容易和小写字母拼音的变量名区别
7 #define指令行的末尾没有分号。
字符输入\输出
8 文本流是由多行字符构成的字符序列,而每行字符则由0个或多个字符组成,行末是一个换行符。标准库负责使每个输入输出流都能够遵循这一模型。
9 文件复制10 任何整型( int )也可以用于存储字符型数据。
void main()
{
int c;
c = getchar(); /*Each time it is called, getchar reads the next input
character from a text stream and returns that as its value*/
while (c != EOF) {
putchar(c);
c = getchar();
}
}
11 EOF定义在头文件<stdio.h>中,是一个整型数。其具体数值并不重要,它与任何char型的值都不相同。
12 赋值可以作为更大的表达式的一部分出现。
#include<stdio.h>
/* copy input tooutput; 2nd version */
void main()
{
int c;
while ((c =getchar()) != EOF)
putchar(c);
}
13 for循环改写
#include <stdio.h>
/* count characters in input; 2nd version */
void main()
{
double nc;
for (nc = 0; gechar() != EOF; ++nc)
;
printf("%.0f\n", nc);/*%.0f强制不打印小数点和小数部分*/
}
14 行计数
/*程序虽然简单,但是确实是经典!*/
#include <stdio.h>
/* count lines in input */
void main()
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
printf("%d\n", nl);
}
15 单词计数
#include <stdio.h>
/*常量,让程序更易读*/
#define IN 1 /* 在单词内 */
#define OUT 0 /* 在单词外 */
/* 统计输入的行数、单词数与字符数 */
void main()
{
int c, nl, nw, nc, state;
state = OUT;/*state记录程序当前是否位于一个单词之中*/
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\n' || c = '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}
16 &&比||高一个优先级。由&&或||连接的表达式由左至右求值,并保证求值过程中只要能够判断最终的结果为真或假,求值就立即终止。
数组
17 统计各个数字、空白符(包括空格、制表符及换行符)及其他字符出现的次数 #include <stdio.h>
void main()
{
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
printf("digits =");
for (i = 0