Why do most C developers use define instead of con

2019-01-10 03:13发布

This question already has an answer here:

In many programs a #define serves the same purpose as a constant. For example.

#define FIELD_WIDTH 10
const int fieldWidth = 10;

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?

9条回答
走好不送
2楼-- · 2019-01-10 04:05

The reason is that most of the time, you want a constant, not a const-qualified variable. The two are not remotely the same in the C language. For example, variables are not valid as part of initializers for static-storage-duration objects, as non-vla array dimensions (for example the size of an array in a structure, or any array pre-C99).

查看更多
等我变得足够好
3楼-- · 2019-01-10 04:12

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.

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.

查看更多
姐就是有狂的资本
4楼-- · 2019-01-10 04:12

Although a const int will not always be appropriate, an enum will usually work as a substitute for the #define if you are defining something to be an integral value. This is actually my preference in such a case.

enum { FIELD_WIDTH = 16384 };
char buf[FIELD_WIDTH];

In C++ this is a huge advantage as you can scope your enum in a class or namespace, whereas you cannot scope a #define.

In C you don't have namespaces and cannot scope an enum inside a struct, and am not even sure you get the type-safety, so I cannot actually see any major advantage, although maybe some C programmer there will point it out to me.

查看更多
登录 后发表回答