2.1 环境
ANSI C的实现中,存在两种不同的环境:1是翻译环境,2是执行环境。
2.1.1 翻译
翻译分几个步骤组成。组成一个程序的每个源文件通过编译过程分别转换为目标代码,各目标文件由链接器捆绑在一起,形成单一而又可执行的文件。链接器也会引用C标准库或个人程序库中需要的文件。
编译过程首先是预处理器处理,然后源代码经过解析后,产生目标代码。
2.1.2 执行
1. 程序必须载入到内存中
2. 启动程序和程序链接起来。
3. 程序在一个堆栈中执行
4. 程序停止
2.2 词法规则
一个ANSI C程序由声明和函数组成。函数定义了需要执行的工作,而声明则描述了函数和函数将要操作的数据类型(有时是数据本身)。注释可以分布在源文件的各个地方。
2.3 程序风格
1. 空行用于分隔不同的逻辑代码段,它们是按照功能分段的。
2. if和相关语句的括号是这些语句的一部分,而不是它们所测试的表达式的一部分,所以在括号和表达式之间留下一个空格,是表达式看上去更突出一些。
3. 在绝大多数操作符的使用中,中间都是隔以空格。
4. 嵌套的语句要注意缩进,用tab键。
5. 注释要成块出现
6. 在函数定义中,返回类型出现于独立的一行中,而函数的名字则在下一行的起始处。
习题:
1.养成习惯,声明放在.h中,定义放在.c中:
negate.h:
int negate(int number);
negate.c:
#include "negate.h"
int negate(int number){
return -number;
}
increment.h:
int increment(int number);
increment.c:
#include "increment.h"
int increment(int number){
return number + 1;
}
main.c:
#include <stdio.h>
#include "increment.h"
#include "negate.h"
main()
{
printf("%d:", increment(10));
printf("%d:", increment(0));
printf("%d\n", increment(-10));
printf("%d:", negate(10));
printf("%d:", negate(0));
printf("%d\n", negate(-10));
}
程序输入输出:
2.
#include <stdio.h>
#include <stdlib.h>
main()
{
int c;
int isRight = 0;
while ((c = getchar()) != EOF){
if (('{' == c) || ('}' == c)){
isRight++;
}
}
if (isRight % 2 == 0){
printf("right");
}
else{
printf("error");
}
}
程序输入输出: