2008年10月22日星期三

C/C++几点知识

1. 为了节省内存,是否该使用char或short取代int做计算?
很早以前就有这个疑问,在C/C++中,若明知自己的计算没有很大,是否可以char或short来取代int以节省内存。C++ Primer 4th在P.38做了以下的建议:

When performing integer arithmetic, it is rarely right to use shorts. In most programs, using shorts leads to mysterious bugs when a value is assigned to a short that is bigger than the largest number it can hold. What happens depends on the machine, but typically the value "wrap around" so that a number too large to fit turns into a large negative numbers. For the same reason, even though char is an integral type, the char type should be used to hold characters and not for computation. The fact that char is signed on some implementations and unsigned on others makes it problematic to use it as a computational type.

2. 浮点运算时,该使用float还是double?
在C++ Primer 4th P.38,对float和double做了以下的建议
Determining which floating-point type to use is easier: It is almost always right to use double. The loss of precission implicit in float is significant, whereas the cost of double precision calculations versus single precision is negligible. In fact, on some machines, double precision is faster than single.

3. i++和++i哪个速度较快?
++i和i++哪个速度较快呢?在C++ Primer 4th整本书中,都是用++i。为什么,答案是因为++i较快,所以C++ Primer才都使用++i。

++i相当于
i = i + 1;
return i;

而i++相当于
int j = i;
i = i+1;
return j;

由于i++还必须copy值给j,所以速度较慢。

4. include了不必要的Header File,是否会增加编译后程序的大小呢?
编译器会根据您所撰写的程序内容自己到所含括进来的头文件去撷取所需要的信息,而没有使用到的信息则不属于这个程序的范围,故不会增加代码的大小。当然,我们也没有必要含括一些没有必要的头文件到程序来,因为这只会徒增程序阅读的困扰。
参考: C语言教学手册 P2-6,洪维恩著

没有评论: