为什么在编程中使用常量?

发布于 2024-09-04 00:19:03 字数 188 浏览 2 评论 0原文

我刚刚使用 Ivor Horton 的 Beginning C 书回顾了一些 C 语言学习。我谈到了关于声明常量的问题,这些常量似乎与同一个句子中的变量混淆了。

只是为了澄清一下,在 C 中指定常量和变量有什​​么区别,实际上,什么时候需要使用常量而不是变量?我知道人们说当信息在程序执行过程中不改变时使用常量,但我真的想不出不能使用变量的时候。

I've just been going back over a bit of C studying using Ivor Horton's Beginning C book. I got to the bit about declaring constants which seems to get mixed up with variables in the same sentence.

Just to clarify, what is the difference in specifying constants and variables in C, and really, when do you need to use a constant instead of a variable? I know folks say to use a constant when the information doesn't change during program execution but I can't really think of a time when a variable couldn't be used instead.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

故事和酒 2024-09-11 00:19:03

正如您可以从名称中猜出的那样,变量会随时间而变化。如果没有变化,就“没有损失”。当您告诉编译器该值不会改变时,编译器可以进行一大堆优化,例如直接内联该值并且从不为堆栈上的常量分配任何空间。

但是,您不能总是指望编译器足够聪明,能够正确确定值一旦设置后是否会更改。在编译器无法以 100% 的置信度确定这一点的任何情况下,编译器都会在安全方面犯错误并假设它可能会更改。这可能会导致各种性能影响,例如避免内联、不优化某些循环、创建不那么并行友好的目标代码。

因此,由于可读性也很重要,因此您应该尽可能使用显式常量,并为实际可以更改的内容保留变量。

至于为什么使用常量而不是文字数字:

1)它使代码更具可读性。每个人都知道 3.14 是什么(希望如此),但不是每个人都知道 3.07 是宾夕法尼亚州的所得税税率。这是特定领域知识的一个例子,并不是每个将来维护你的代码(例如税务软件)的人都会知道它。

2) 进行更改时可以节省工作量。如果以后税率有变化,每3.07到3.18就去换一下,会很烦人。您总是希望尽量减少更改,最好只进行一次更改。您必须进行的并发更改越多,您忘记某些内容并导致错误的风险就越高。

3) 您可以避免危险的错误。想象一下,有两个州的所得税率为 3.05,然后其中一个州变为 3.18,而另一个州则保持 3.07。如果只是进行替换,您最终可能会犯下严重错误。当然,许多整数或字符串常量值比“3.07”更常见。例如,数字 7 可以代表一周中的天数或其他内容。在大型程序中,很难确定每个文字值的含义。

4)对于字符串文本,通常对字符串使用符号名称,以允许字符串池在支持多种语言的情况下快速更改。

注意,除了变量和“常量变量”之外,还有一些语言带有枚举。枚举实际上允许您为一小组常量(例如返回值)定义类型,因此使用它们将提供类型安全性。

例如,如果我有一个星期几和几个月的枚举,如果我将一个月分配到一天中,我会收到警告。如果我只使用整数常量,则将第 3 天分配给第 3 个月时不会出现警告。您始终需要类型安全,并且它提高了可读性。枚举也更适合定义顺序。想象一下,您对一周中的几天有常数,现在您希望一周从星期一而不是星期日开始。

A variable, as you can guess from the name, varies over time. If it doesn't vary, there is "no loss". When you tell the compiler that the value will not change, the compiler can do a whole bunch of optimizations, like directly inlining the value and never allocating any space for the constant on the stack.

However, you cannot always count on your compiler to be smart enough to be able to correctly determine if a value will change once set. In any situation where the compiler is incapable of determining this with 100% confidence, the compiler will err on the side of safety and assume it could change. This can result in various performance impacts like avoiding inlining, not optimizing certain loops, creating object code that is not as parallelism-friendly.

Because of this, and since readability is also important, you should strive to use an explicit constant whenever possible and leave variables for things that can actually change.

As to why constants are used instead of literal numbers:

1) It makes code more readable. Everyone knows what 3.14 is (hopefully), not everyone knows that 3.07 is the income tax rate in PA. This is an example of domain-specific knowledge, and not everyone maintaining your code in the future (e.g., a tax software) will know it.

2) It saves work when you make a change. Going and changing every 3.07 to 3.18 if the tax rate changes in the future will be annoying. You always want to minimize changes and ideally make a single change. The more concurrent changes you have to make, the higher the risk that you will forget something, leading to errors.

3) You avoid risky errors. Imagine that there were two states with an income tax rate of 3.05, and then one of them changes to 3.18 while the other stays at 3.07. By just going and replacing, you could end up with severe errors. Of course, many integer or string constant values are more common than "3.07". For example, the number 7 could represent the number of days in the week, and something else. In large programs, it is very difficult to determine what each literal value means.

4) In the case of string text, it is common to use symbolic names for strings to allow the string pools to change quickly in the case of supporting multiple languages.

Note that in addition to variables and "constant variables", there are also some languages with enumerations. An enumeration actually allows you to defines a type for a small group of constants (e.g., return values), so using them will provide type safety.

For example, if I have an enumeration for the days of the weeks and for the months, I will be warned if I assign a month into a day. If I just use integer constants, there will be no warning when day 3 is assigned to month 3. You always want type safety, and it improves readability. Enumerations are also better for defining order. Imagine that you have constants for the days of the week, and now you want your week to start on Monday rather than Sunday.

故事灯 2024-09-11 00:19:03

使用常量更多的是一种防御性编程方式,可以保护自己免受伤害,避免在凌晨 2 点或喝咖啡之前编码时意外更改代码中某处的值。

从技术上讲,是的,您可以使用变量来代替。

Using constants is more a way of defensive programming, to protect yourself from yourself, from accidentally changing the value somewhere in the code when you're coding at 2 a.m. or before having drunk your coffee.

Technically, yes, you can use a variable instead.

冧九 2024-09-11 00:19:03

与变量相比,常量有几个优点。

常量提供了某种程度的保证,即代码无法更改底层值。这对于较小的项目来说并不重要,但对于具有多个作者编写的多个组件的较大项目来说很重要。

常量还为编译器进行优化提供了强有力的提示。由于编译器知道该值无法更改,因此不需要从内存加载该值,并且可以优化代码以仅适用于常量的精确值(例如,编译器可以使用移位来进行乘法/除法)如果 const 是 2 的幂。)

常量本质上也是静态的 - 您可以在头文件中声明常量及其值,而不必担心将其定义在一个地方。

Constants have several advantages over variables.

Constants provide some level of guarantee that code can't change the underlying value. This is not of much importance for a smaller project, but matters on a larger project with multiple components written by multiple authors.

Constants also provide a strong hint to the compiler for optimization. Since the compiler knows the value can't change, it doesn't need to load the value from memory and can optimize the code to work for only the exact value of the constant (for instance, the compiler can use shifts for multiplication/division if the const is a power of 2.)

Constants are also inherently static - you can declare the constant and its value in a header file, and not have to worry about defining it exactly one place.

伴梦长久 2024-09-11 00:19:03

其一,性能优化。

更重要的是,这是针对人类读者的。请记住,您的目标受众不仅仅是编译器。它有助于用代码表达自己,并避免注释。

const int spaceTimeDimensions = 4;

if(gpsSattelitesAvailable >= spaceTimeDimensions)
  Good();

For one, performance optimization.

More importantly, this is for human readers. Remember that your target audience is not only the compiler. It helps to express yourself in code, and avoid comments.

const int spaceTimeDimensions = 4;

if(gpsSattelitesAvailable >= spaceTimeDimensions)
  Good();
吾家有女初长成 2024-09-11 00:19:03

对于像 C 这样的低级语言,常量允许进行多种编译优化。

对于一般的编程语言来说,你并不真正需要它们。高级动态语言(例如 Ruby 和 JavaScript)没有它们(或者至少在真正的常量意义上没有)。正如您所建议的那样,而是使用变量。

For a low-level language like C, constants allow for several compilation optimizations.

For a programming language in general, you don't really need them. High level dynamic languages such as Ruby and JavaScript doesn't have them (or at least not in a true constant sense). Variables are used instead, just like you suggested.

星軌x 2024-09-11 00:19:03

恒定是指您只想共享内存,并且它不会改变。

Constant is when you just want to share the memory, and it doesn't change.

素罗衫 2024-09-11 00:19:03

const 关键字通常用于函数参数,特别是指针,以表明指针指向的内存不会被函数修改。例如,查看 strcpy 的声明:

char *strcpy(char *dest, const char *src);

否则,例如,

const int my_magic_no = 54321;

可能会优先使用以下声明:

#define MY_MAGIC_NO 54321

出于类型安全原因,

The const keyword is often used for function parameters, particularly pointers, to suggest the memory the pointer points to will not be modified by the function. Look at the decleration for strcpy for instance:

char *strcpy(char *dest, const char *src);

Otherwise, for example, an declaration such as

const int my_magic_no = 54321;

might be preferred over:

#define MY_MAGIC_NO 54321

for type safety reasons.

说好的呢 2024-09-11 00:19:03

这是捕获某一类错误的非常简单的方法。如果您声明了一个变量 const,并且意外地尝试修改它,编译器将调用您的变量。

It's a really easy way to trap a certain class of errors. If you declare a variable const, and accidentally try to modify it, the compiler will call you on it.

抹茶夏天i‖ 2024-09-11 00:19:03

对于任何目的的变量声明和初始化来说,常量都是非常必要的,例如在循环开始时、检查 if -else 语句中的条件等。

有关更多参考,请随意阅读以下两篇文章:

Constants are very necessary in regards to declaration and intialization of variable for any purpose such as at the starting of the loop, to check the condition within the if -else statement, etc.

For more reference, feel free to read either of the following articles:

心碎无痕… 2024-09-11 00:19:03

不使用 const 可能意味着团队项目中的某人可以声明 where int FORTY_TWO = 42 并由其他团队成员在其他地方使其等于 FORTY_TWO = 41。因此世界末日发生了,你也失去了生命的答案。使用 const 尽管这一切都不会发生。另外,与普通变量的存储相比,const 存储在内存中的其他位置,并且效率更高。

Not using const can mean someone in a team project could declare where int FORTY_TWO = 42 and make it equal FORTY_TWO = 41 somewhere else by another team member. Therefore the end of the world happens and you also loose the answer to life. with const although none of this will ever happen. Plus const is stored elsewhere in memory, when compared to the storage of normal variables, and is more efficient.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文