C语言 为什么在编程中使用常量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2953601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why use constants in programming?
提问by Adam N
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.
我刚刚使用 Ivor Horton 的 Beginning C 书回顾了一些 C 学习。我谈到了在同一个句子中声明似乎与变量混淆的常量。
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.
为了澄清一下,在 C 中指定常量和变量有什么区别,实际上,什么时候需要使用常量而不是变量?我知道人们说在程序执行期间信息没有改变时使用常量,但我真的想不出什么时候不能使用变量。
回答by Uri
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.
但是,您不能总是指望您的编译器足够聪明,能够正确确定设置后是否会更改值。在编译器无法以 100% 置信度确定这一点的任何情况下,编译器都会在安全方面出错并假设它可能会改变。这可能会导致各种性能影响,例如避免内联、不优化某些循环、创建对并行性不太友好的目标代码。
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.
1)它使代码更具可读性。每个人都知道 3.14 是什么(希望如此),并不是每个人都知道 3.07 是 PA 的所得税税率。这是特定领域知识的一个例子,并不是每个人在未来维护您的代码(例如,税务软件)都会知道它。
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.
2)当您进行更改时,它可以节省工作。如果以后税率发生变化,每3.07到3.18就去换一次会很烦人。您总是希望尽量减少更改,最好只进行一次更改。您必须进行的并发更改越多,您忘记某些事情并导致错误的风险就越高。
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.
3) 你避免了危险的错误。假设有两个州的所得税率为 3.05,然后其中一个更改为 3.18,而另一个保持在 3.07。只是去替换,你最终可能会遇到严重的错误。当然,许多整数或字符串常量值比“3.07”更常见。例如,数字 7 可以表示一周中的天数,以及其他内容。在大型程序中,很难确定每个字面值的含义。
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.
4)在字符串文本的情况下,通常对字符串使用符号名,以允许字符串池在支持多语言的情况下快速变化。
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.
例如,如果我对周中的天数和月份进行了枚举,如果我将一个月分配到一天中,我将收到警告。如果我只使用整数常量,当第 3 天被分配到第 3 个月时不会有警告。你总是想要类型安全,它提高了可读性。枚举也更适合定义顺序。想象一下,您有一周中各天的常量,现在您希望您的一周从星期一而不是星期日开始。
回答by Adam N
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.
使用常量更像是一种防御性编程方式,可以保护自己免受自己的伤害,以免在凌晨 2 点编写代码或喝咖啡之前意外更改代码中某处的值。
Technically, yes, you can use a variable instead.
从技术上讲,是的,您可以改用变量。
回答by Michael
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.)
常量还为编译器提供了一个强有力的优化提示。由于编译器知道该值不能改变,它不需要从内存中加载该值,并且可以优化代码以仅适用于常量的确切值(例如,编译器可以使用移位进行乘法/除法)如果 const 是 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.
常量本质上也是静态的——您可以在头文件中声明常量及其值,而不必担心在一个地方定义它。
回答by Pavel Radzivilovsky
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();
回答by Jakob
For a low-level language like C, constants allow for several compilation optimizations.
对于像 C 这样的低级语言,常量允许进行多种编译优化。
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.
对于一般的编程语言,您并不真正需要它们。Ruby 和 JavaScript 等高级动态语言没有它们(或者至少不是真正意义上的常量)。就像您建议的那样,使用变量代替。
回答by Jakob
Constant is when you just want to share the memory, and it doesn't change.
常量是当你只想共享内存时,它不会改变。
回答by James Morris
The constkeyword 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 strcpyfor instance:
该const关键字通常用于函数参数,特别是指针,以表明指针指向的内存不会被函数修改。看看 declerationstrcpy例如:
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.
出于类型安全原因。
回答by crazyscot
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.
这是捕获某类错误的非常简单的方法。如果你声明了一个变量const,并且不小心尝试修改它,编译器会调用它。
回答by yogi
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.
常量对于任何目的的变量声明和初始化都是非常必要的,例如在循环开始时,检查 if -else 语句中的条件等。
For more reference, feel free to read either of the following articles:
如需更多参考,请随时阅读以下文章之一:
回答by yogi
Not using const can mean someone in a team project could declare where int FORTY_TWO = 42and make it equal FORTY_TWO = 41somewhere else by another team member. Therefore the end of the world happens and you also loose the answer to life. with constalthough none of this will ever happen. Plus constis stored elsewhere in memory, when compared to the storage of normal variables, and is more efficient.
不使用 const 可能意味着团队项目中的某个人可以声明 where并由另一个团队成员在其他地方int FORTY_TWO = 42使其相等FORTY_TWO = 41。因此,世界末日发生了,你也失去了生命的答案。与const虽然没有这将不会发生。const与普通变量的存储相比,Plus存储在内存中的其他地方,并且效率更高。

