大多数C开发人员为什么要使用定义的,而不是常量? [英] Why do most C developers use define instead of const?
问题描述
在许多程序的的#define
有异曲同工之妙的一个常数。例如。
In many programs a #define
serves the same purpose as a constant. For example.
#define FIELD_WIDTH 10
const int fieldWidth = 10;
我经常看到pferred比其他第一种形式$ P $,依托pre-处理器来处理基本上是从一个应用程序的决定。是否有此传统,什么原因呢?
I commonly see the first form preferred over the other, relying on the pre-processor to handle what is basically an application decision. Is there a reason for this tradition?
推荐答案
有是这是一个非常坚实的理由:常量
在C不意味着什么是不变的。这只是意味着一个变量是只读的。
There is a very solid reason for this: const
in C does not mean something is constant. It just means a variable is read-only.
在地方,编译器需要一个真正的常数(如数组大小非VLA阵列),使用常量
变量,如 fieldWidth
是不可能的。
In places where the compiler requires a true constant (such as for array sizes for non-VLA arrays), using a const
variable, such as fieldWidth
is just not possible.
这篇关于大多数C开发人员为什么要使用定义的,而不是常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!