(原創) 为了节省内存,是否该使用char或short取代int做计算? (C/C++)

我很早以前就有这个疑问,在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.

Reference
C++ Primer 4th P.38

posted on 2006-10-04 16:06  真 OO无双  阅读(1508)  评论(0编辑  收藏  举报

导航