现在的位置: 首页 > 综合 > 正文

读《The C Programming Language》(4)

2013年08月18日 ⁄ 综合 ⁄ 共 1605字 ⁄ 字号 评论关闭

读完了第二章:类型,运算符和表达式。下面列举一些有启发的点:

  • 关于类型(Type),作者用一句话很精辟地作了概括:"The type of an object determines the set of values it can have and what operations can be performed on it."一个对象的类型决定了它能够取值的集合以及能对它进行的操作。
  • 关于变量名,许多类C高级语言的编程规范都推荐类字段的名字以下划线"_"开始,但在C语言中,所有的变量名都不推荐用"_"开始。作者说"Don't begin variable names with underscore, however, since library routines often use such names."因为库程序会使用这样的名字。
  • 整形类型分为short, int和long,它们的长度怎么区分?作者指出,"The intent is that short and long should provide different lengths of integers where practical; int will normally be the natural size for a particular machine."所以在现在的32位机器上,int型的长度就是32。"where practical"意思是short和long的长度是由编译器决定的,只要short不比int长,int不比long长就可以。在16位的机器上,short和int都是16位长。和整形类似,float, double和long double的长度也是依赖于具体的机器的。它们可以代表一种、两种或者三种不同的长度。
  • 常数的前缀和后缀。前缀有0(八进制)和0x(十六进制),后缀有U(unsigned)、L(long)和F(float)。前缀和后缀可以同时加,比如OxFUL。
  • 关于为什么不用整形常量直接代替字符型常量,如48代替'0',作者解释说,"If we write '0' instead of a numeric value like 48 that depends on the character set, the program is independent of the particular value and easier to read."由此可见,字符型常量虽然内部存的是一个整形值,但这个值取决于机器的字符集。设立字符型常量可以使字符独立于具体的字符集,并增加程序可读性。
  • 用八进制和十六机制表示字符,分别采用下面的形式:'/ooo'和'/xhh'。它们都是一个字符,值为一个整数。
  • 关于'/0',作者提到,"The character constant '/0' represents the character with value zero, the null character. '/0' is often written instead of 0 to emphasize the character nature of some expression, but the numeric value is just 0"。'/0'的值就是0,写成这样只是为了强调它的字符属性。
  • 浮点数还可以这样被赋值:float eps = 1.0e-5;,以前没有注意过。
  • 非局部变量只能被初始化一次,并且只能被初始化一个常量表达式。外部变量和静态变量缺省被初始化成0,而未被初始化的局部变量则有不确定的值。
  • const可以被用在数组参数上,以防止数组被调用的函数改变。如:int strlen(const char[]);
  • 这个getbits函数写得很漂亮,从中可以得到不少关于位操作的启发:
    /* getbits: get n bits from position p */
    unsigned getbits(unsigned x, int p, int n)
    {
        return (x >> (p+1-n)) & ~(~0 << n);
    }
    用求反运算符~使得程序独立于具体机器的字长,因而具有可移植性。

抱歉!评论已关闭.