大多数C开发人员为什么要使用定义的,而不是常量? [英] Why do most C developers use define instead of const?

查看:106
本文介绍了大多数C开发人员为什么要使用定义的,而不是常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多程序的的#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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆