女性得乙肝有什么症状| 子官肌瘤吃什么食物| 蛞蝓是什么动物| 半身不遂是什么意思| 胃食管反流挂什么科| 头皮屑多是什么原因| 什么情况下需要打破伤风| 什么叫人格| 什么食物补气| 百岁老人叫什么| 芒果有什么营养| 凌晨三四点是什么时辰| 修身养性下一句是什么| 男人肝火旺吃什么药| 汗味酸臭是什么原因| 呼吸内科主要看什么病| 有口无心是什么意思| 最贵的金属是什么| yp什么意思| 打葡萄糖点滴有什么用| 海丽汉森是什么档次| 尿酸高吃什么食物好| 女人吃什么补充雌激素| 人什么什么事的成语| 喝什么茶去湿气| 梦到拔牙是什么预兆| 颈动脉彩超查什么| 噬血细胞综合征是什么病| 宫保鸡丁属于什么菜系| 胳膊肘疼痛是什么原因| 大运正官是什么意思| 什么书什么画| 克罗心是什么档次| 见红的血是什么颜色| 榴莲吃了对身体有什么好处| 法院庭长是什么级别| 左手臂有痣代表什么| 火旺是什么意思| 动车跟高铁有什么区别| 过境签是什么意思| 尿酸高中医叫什么病| 看肾挂什么科| 离异什么意思| 海南的海是什么海| 特朗普为什么叫川普| 处女座上升星座是什么| 做tct检查前要注意什么| 婆娑是什么意思| 斯字五行属什么| 子宫肌瘤吃什么食物好| 男人右眉毛里有痣代表什么| 69是什么| 十一月是什么月| 吃纳豆有什么好处| b型血和o型血生的孩子是什么血型| 梦到洗衣服是什么意思| 梦到钱丢了预示着什么| 玄色是什么颜色| 杀破狼是什么意思| 什么情况下会得甲亢| 孕反应最早什么时候开始| 动脉钙化是什么意思| 鹊桥是什么意思| 手脱皮用什么药膏最好| 哼哼唧唧是什么生肖| 碱性磷酸酶偏低是什么原因| 盐洗脸有什么好处| 伊人什么意思| 明朝为什么会灭亡| 经常放臭屁是什么原因| 额是什么意思| 4月25号是什么星座| 眼压高要注意什么| 退位让贤是什么意思| 腺病是什么意思| 马代表什么数字| 做透析是什么病| 逆商是什么| 取环需要做什么检查| 验孕棒阳性代表什么| 1963年属什么生肖| 绿色衣服搭配什么颜色的裤子| anker是什么牌子| 什么样的脚好看| 中医治未病是什么意思| 盎司是什么意思| 州和洲有什么区别| 越字五行属什么| 疱疹用什么药好得快| 高压是什么意思| 为什么越累越胖| 渣男最怕什么样的女人| 十月份生日是什么星座| 楚国是现在的什么地方| 排湿气最快的方法吃什么| 什么是血小板| 维生素h是什么| 阴超能检查出什么| 肛门周边瘙痒擦什么药| 一线炎是什么病严重吗| 隐形眼镜半年抛是什么意思| cfu是什么单位| 夏天盖什么被子最舒服| 女性肾虚吃什么药| 半边脸疼是什么原因| 豚鼠吃什么| 陈小春什么星座| 奶茶喝多了有什么危害| 疱疹挂号挂什么科室| loho是什么牌子| 马赛克是什么| 茉莉花茶有什么作用| 吊膀子是什么意思| 农历八月初三是什么星座| 什么行业赚钱| 交通运输是干什么的| 压力大会有什么症状| 镜花水月什么意思| 刚感染艾滋病什么症状| 69是什么意思| 身体逐渐消瘦是什么原因| 皖鱼是什么鱼| 汕头有什么好玩的景点| 膳食纤维是什么| 不怀孕是什么原因引起的| 很会放屁是什么原因| 什么风大雨| 什么是戒断反应| 表姐的孩子叫我什么| 为什么会得面瘫| 抗坏血酸是什么意思| 血糖降不下来是什么原因导致| 火腿肠是什么做的| 下午三点到四点是什么时辰| 冰心原名叫什么| 柱状上皮外移什么意思| 苍苍什么| 红斑狼疮是什么病| 云南小黄姜有什么功效| 泄气的意思是什么| 香仪是什么意思| 屌丝是什么| 烀是什么意思| 桂鱼吃什么食物| 寄生虫感染吃什么药| 4月8日是什么星座| 发烧咳嗽吃什么药| 什么东西去火| 家是什么| 慢性活动性胃炎是什么意思| 卡裆是什么意思啊| 支原体感染是什么意思| 为什么容易出汗| 吃中药忌口都忌什么| 盆腔炎吃什么药效果最好| 女人更年期有什么症状| 维生素b是什么| 印象是什么意思| 日记可以写什么| 什么时候开始降温| 挥霍是什么意思| 梦见舅舅是什么意思| 女人腰椎疼是什么原因| 桑葚泡水喝有什么好处| 白癜风是什么病| 糖原是什么| 梦见长牙齿预示着什么| 舌头根发麻是什么原因| 胃肠型感冒吃什么药| 脚上长疣是什么原因| 什么药可以治早迣| 什么东西最贵| 肺部钙化灶是什么意思| 双侧输尿管不扩张是什么意思| 琥珀是什么意思| 20度穿什么衣服合适| 当所有的人离开我的时候是什么歌| 性是什么| 五指毛桃长什么样| 眼睛肿是什么原因| 如何查自己是什么命格| 75c是什么罩杯| 食道不舒服挂什么科| 什么牌子的保温杯好| 五彩的什么| 03年是什么年| 为什么鱼和熊掌不可兼得| 棒槌是什么意思| 男性漏尿是什么原因| 头晕需要做什么检查| 什么是顶香人| 小狗吐白沫不吃东西没精神吃什么药| 转氨酶高吃什么药好| 尿频尿急小腹胀痛吃什么药| 瑶柱是什么东西| 上颚痒是什么原因| 湿疹什么样| 睡觉时胳膊和手发麻是什么原因| 广州为什么叫羊城| 羊的守护神是什么菩萨| 妥了是什么意思| 什么是煞气| hcg是什么意思| 售馨是什么意思| 蛇是什么类动物| 结婚登记需要什么| 月经提前是什么原因| 水煮鱼一般用什么鱼| 吃什么丰胸效果最好最快| oto是什么意思| 巨蟹座和什么星座最配| 什么是色弱| 蛇七寸是什么部位| 鲁迅是什么样的人| 避孕药有什么副作用| 为什么头会一阵一阵的痛| 入睡困难吃什么中成药| 椎管狭窄吃什么药| 朱迅是什么民族| 胎膜早破是什么原因引起的| 右胳膊麻木是什么征兆| 实拍是什么意思| below是什么意思| 老打嗝什么原因| 跑步配速什么意思| 解脲脲原体是什么意思| 腈纶是什么面料优缺点| 争先恐后是什么生肖| 省委巡视组组长什么级别| 紫花地丁有什么功效| 大便溏稀吃什么药| 耳朵响是什么原因引起的| 为什么会脑供血不足| 走路脚心疼是什么原因| 什么树叶| 男人阴虱用什么药| 手臂疼痛挂什么科| 肌肉损伤吃什么药| 台湾为什么叫4v| 湿吻是什么意思| 多晒太阳有什么好处| 什么样的人不能坐飞机| 胃气胃胀吃什么药最好| 湿疹为什么一热就出来| 跳蚤咬了擦什么药最好| 青柠是什么意思| hca是什么意思| 人外是什么意思| 领衔是什么意思| 94岁属什么| 芹菜和西芹有什么区别| 超声波是什么意思| 218号是什么星座| 杨贵妃属什么生肖| 禅悟是什么意思| 完谷不化吃什么中成药| co是什么元素| 两横一竖是什么字| 主任医师是什么职称| 七月份可以种什么菜| 糙米是什么| 1984年属鼠五行属什么| 什么是肝性脑病| 健身吃蛋白粉有什么好处和坏处| 百度
百度 成就百年大业,既是天意,更是人心,在林州百姓心中,杨贵是一座不朽的丰碑,是红旗渠精神之魂。

In computer programming, a constant is a value that is not altered by the program during normal execution. When associated with an identifier, a constant is said to be "named," although the terms "constant" and "named constant" are often used interchangeably. This is contrasted with a variable, which is an identifier with a value that can be changed during normal execution. To simplify, constants' values remains, while the values of variables varies, hence both their names.

Constants are useful for both programmers and compilers: for programmers, they are a form of self-documenting code and allow reasoning about correctness, while for compilers, they allow compile-time and run-time checks that verify that constancy assumptions are not violated,[a] and allow or simplify some compiler optimizations.

There are various specific realizations of the general notion of a constant, with subtle distinctions that are often overlooked. The most significant are: compile-time (statically valued) constants, run-time (dynamically valued) constants, immutable objects, and constant types (const).

Typical examples of compile-time constants include mathematical constants, values from standards (here maximum transmission unit), or internal configuration values (here characters per line), such as these C examples:

const float PI = 3.1415927;  // maximal single float precision
const unsigned int MTU = 1500;  // Ethernet v2, RFC 894
const unsigned int COLUMNS = 80;

Typical examples of run-time constants are values calculated based on inputs to a function, such as this C++ example:

void f(std::string s) {
  const size_t l = s.length();
  // ...
}

Some programming languages make an explicit syntactic distinction between constant and variable symbols, for example considering assignment to a constant to be a syntax error, while in other languages they are considered syntactically the same (both simply an identifier), and the difference in treatment is semantic (assignment to an identifier is syntactically valid, but if the identifier is a constant it is semantically invalid).

A constant value is defined once and can be referenced many times throughout a program. Using a constant instead of specifying the same value multiple times can simplify code maintenance (as in don't repeat yourself) and can be self documenting by supplying a meaningful name for a value, for instance, PI instead of 3.1415926.

Comparison with literals and macros

edit

There are several main ways to express a data value that doesn't change during program execution that are consistent across a wide variety of programming languages. One very basic way is by simply writing a literal number, character, or string into the program code, which is straightforward in C, C++, and similar languages.

In assembly language, literal numbers and characters are done using the "immediate mode" instructions available on most microprocessors. The name "immediate" comes from the values being available immediately from the instruction stream, as opposed to loading them indirectly by looking up a memory address.[1] On the other hand, values longer than the microprocessor's word length, such as strings and arrays, are handled indirectly and assemblers generally provide a "data" pseudo-op to embed such data tables in a program.

Another way is by defining a symbolic macro. Many high-level programming languages, and many assemblers, offer a macro facility where the programmer can define, generally at the beginning of a source file or in a separate definition file, names for different values. A preprocessor then replaces these names with the appropriate values before compiling, resulting in something functionally identical to using literals, with the speed advantages of immediate mode. Because it can be difficult to maintain code where all values are written literally, if a value is used in any repetitive or non-obvious way, it is often named by a macro.

A third way is by declaring and defining a variable as being "constant". A global variable or static variable can be declared (or a symbol defined in assembly) with a keyword qualifier such as const, constant, or final, meaning that its value will be set at compile time and should not be changeable at runtime. Compilers generally put static constants in the text section of an object file along with the code itself, as opposed to the data section where non-const initialized data is kept. Some compilers can produce a section specifically dedicated to constants. Memory protection can be applied to this area to prevent overwriting of such constants by errant pointers.

These constants differ from literals in a number of ways. Compilers generally place a constant in a single memory location identified by symbol, rather than spread throughout the executable as with a macro. While this precludes the speed advantages of immediate mode, there are advantages in memory efficiency, and debuggers can work with these constants at runtime. Also while macros may be redefined accidentally by conflicting header files in C and C++, conflicting constants are detected at compile time.

Depending upon the language, constants can be untyped or typed. In C and C++, macros provide the former, while const provides the latter:

#define PI 3.1415926535

const float pi2 = 3.1415926535;

while in Ada, there are universal numeric types that can be used, if desired:

pi : constant := 3.1415926535;

pi2 : constant float := 3.1415926535;

with the untyped variant being implicitly converted to the appropriate type upon each use.[2]

Dynamically-valued constants

edit

Besides the static constants described above, many procedural languages such as Ada and C++ extend the concept of constantness toward global variables that are created at initialization time, local variables that are automatically created at runtime on the stack or in registers, to dynamically allocated memory that is accessed by pointer, and to parameter lists in function headers.

Dynamically valued constants do not designate a variable as residing in a specific region of memory, nor are the values set at compile time. In C++ code such as

float func(const float ANYTHING) {
    const float XYZ = someGlobalVariable*someOtherFunction(ANYTHING);
    ...
}

the expression that the constant is initialized to are not themselves constant. Use of constantness is not necessary here for program legality or semantic correctness, but has three advantages:

  1. It is clear to the reader that the object will not be modified further, once set
  2. Attempts to change the value of the object (by later programmers who do not fully understand the program logic) will be rejected by the compiler
  3. The compiler may be able to perform code optimizations knowing that the value of the object will not change once created.[3]

Dynamically valued constants originated as a language feature with ALGOL 68.[3] Studies of Ada and C++ code have shown that dynamically valued constants are used infrequently, typically for 1% or less of objects, when they could be used much more, as some 40–50% of local, non-class objects are actually invariant once created.[3][4] On the other hand, such "immutable variables" tend to be the default in functional languages since they favour programming styles with no side-effect (e.g., recursion) or make most declarations immutable by default, such as ML. Purely functional languages even forbid side-effects entirely.

Constantness is often used in function declarations, as a promise that when an object is passed by reference, the called function will not change it. Depending on the syntax, either a pointer or the object being pointed to may be constant, however normally the latter is desired. Especially in C++ and C, the discipline of ensuring that the proper data structures are constant throughout the program is called const-correctness.

Constant function parameters

edit

In C/C++, it is possible to declare the parameter of a function or method as constant. This is a guarantee that this parameter cannot be inadvertently modified after its initialization by the caller. If the parameter is a pre-defined (built-in) type, it is called by value and cannot be modified. If it is a user-defined type, the variable is the pointer address, which cannot be modified either. However, the content of the object can be modified without limits. Declaring parameters as constants may be a way to signalise that this value should not be changed, but the programmer must keep in mind that checks about modification of an object cannot be done by the compiler.

Besides this feature, it is in C++ also possible to declare a function or method as const. This prevents such functions or methods from modifying anything but local variables.

In C#, the keyword const exists, but does not have the same effect for function parameters, as it is the case in C/C++. There is, however, a way to "stir" the compiler to do make the check, albeit it is a bit tricky.[5]

Object-oriented constants

edit

A constant data structure or object is referred to as "immutable" in object-oriented parlance. An object being immutable confers some advantages in program design. For instance, it may be "copied" simply by copying its pointer or reference, avoiding a time-consuming copy operation and conserving memory.

Object-oriented languages such as C++ extend constantness even further. Individual members of a struct or class may be made const even if the class is not. Conversely, the mutable keyword allows a class member to be changed even if an object was instantiated as const.

Even functions can be const in C++. The meaning here is that only a const function may be called for an object instantiated as const; a const function doesn't change any non-mutable data.

C# has both a const and a readonly qualifier; its const is only for compile-time constants, while readonly can be used in constructors and other runtime applications.

Java

edit

Java has a qualifier called final that prevents changing a reference and makes sure it will never point to a different object. This does not prevent changes to the referred object itself. Java's final is basically equivalent to a const pointer in C++. It does not provide the other features of const.

In Java, the qualifier final states that the affected data member or variable is not assignable, as below:

final int i = 3;
i = 4; // Error! Cannot modify a "final" object

It must be decidable by the compilers where the variable with the final marker is initialized, and it must be performed only once, or the class will not compile. Java's final and C++'s const keywords have the same meaning when applied with primitive variables.

const int i = 3; // C++ declaration
i = 4; // Error!

Considering pointers, a final reference in Java means something similar to const pointer in C++. In C++, one can declare a "constant pointer type".

Foo *const bar = mem_location; // const pointer type

Here, bar must be initialised at the time of declaration and cannot be changed again, but what it points is modifiable. I.e. *bar = value is valid. It just can't point to another location. Final references in Java work the same way except that they can be declared uninitialized.

final Foo i; // a Java declaration

Note: Java does not support pointers.[6] It is because pointers (with restrictions) are the default way of accessing objects in Java, and Java does not use stars to indicate them. For example, i in the last example is a pointer and can be used to access the instance.

One can also declare a pointer to "read-only" data in C++.

const Foo *bar;

Here bar can be modified to point anything, anytime; just that pointed value cannot be modified through bar pointer.

There is no equivalent mechanism in Java. Thus there are also no const methods. Const-correctness cannot be enforced in Java, although by use of interfaces and defining a read-only interface to the class and passing this around, one can ensure that objects can be passed around the system in a way that they cannot be modified.

Java collections framework provides a way to create an immutable wrapper of a Collection via Collections.unmodifiableCollection() and similar methods.

A method in Java can be declared "final", meaning that it cannot be overridden in subclasses.

In C#, the qualifier readonly has the same effect on data members that final does in Java and the const does in C++; the modifier const has an effect similar (yet typed and class-scoped) to that of #define in C++. The other, inheritance-inhibiting effect of Java's final when applied to methods and classes is induced in C# with the aid of the keyword sealed.

Unlike C++, C# does not permit methods and parameters to be marked as const. However one may also pass around read-only subclasses, and the .NET Framework provides some support for converting mutable collections to immutable ones which may be passed as read-only wrappers.

By paradigm

edit

Treatment of constants varies significantly by programming paradigm. Const-correctness is an issue in imperative languages like C++ because by default name bindings typically create variables, which can vary, as the name suggests, and thus if one wishes to mark a binding as constant this requires some additional indication.[b] In other programming language paradigms related issues arise, with some analogs to const-correctness found.

In functional programming, data are typically constant by default, rather than variable by default. Instead of assigning a value to a variable (a storage space with a name and potentially variable value), one creates a binding of a name to a value, such as by the let construct in many dialects of Lisp. In some functional languages, particularly multiparadigm ones such as Common Lisp, modifying data is commonplace, while in others it is avoided or considered exceptional; this is the case for Scheme (another Lisp dialect), which uses the set! construct to modify data, with the ! exclamation point drawing attention to this. Such languages achieve the goals of const-correctness by default, drawing attention to modification rather than constantness.

In a number of object-oriented languages, there is the concept of an immutable object, which is particularly used for basic types like strings; notable examples include Java, JavaScript, Python, and C#. These languages vary in whether user-defined types can be marked as immutable, and may allow particular fields (attributes) of an object or type to be marked as immutable.

In some multiparadigm languages that allow both object-oriented and functional styles, both of these features may be combined. For example, in OCaml object fields are immutable by default and must be explicitly marked with the keyword mutable to be mutable, while in Scala, bindings are explicitly immutable when defined with val for "value" and explicitly mutable when defined with var for "variable".

Naming conventions

edit

Naming conventions for constants vary. Some simply name them as they would any other variable. Others use capitals and underscores for constants in a way similar to their traditional use for symbolic macros, such as SOME_CONSTANT.[7] In Hungarian notation, a "k" prefix signifies constants as well as macros and enumerated types.

One enforced convention is that in Ruby, any variable that begins with a capital letter is considered a constant, including class names.

See also

edit

Notes

edit
  1. ^ In some cases this can be circumvented, e.g. using self-modifying code or by overwriting the memory location where the value is stored.
  2. ^ This is not universal: in Ada input parameters and loop parameters are implicitly constant, for instance.

References

edit
  1. ^ Ex. IBM Systems Information. Instruction Set - Assembler Language Reference for PowerPC.
  2. ^ Booch, Grady (1983). Software Engineering with Ada. Benjamin Cummings. pp. 116–117. ISBN 0-8053-0600-5.
  3. ^ a b c Schilling, Jonathan L. (April 1995). "Dynamically-Valued Constants: An Underused Language Feature". SIGPLAN Notices. 30 (4): 13–20. doi:10.1145/202176.202177. S2CID 17489672.
  4. ^ Perkins, J. A. Programming Practices: Analysis of Ada Source Developed for the Air Force, Army, and Navy. Proceedings TRI-Ada '89. pp. 342–354. doi:10.1145/74261.74287.
  5. ^ Timwi (2025-08-07). "Read-only ("const"-like) function parameters of C#". Stack Overflow. Retrieved 2025-08-07. [...] Then you can declare methods whose parameter type "tells" whether it plans on changing the variable or not:. [...] This mimics compile-time checks similar to constness in C++. As Eric Lippert correctly pointed out, this is not the same as immutability. But as a C++ programmer I think you know that.
  6. ^ "Oracle Technology Network for Java Developers | Oracle Technology Network | Oracle". Java.sun.com. 2025-08-07. Retrieved 2025-08-07.
  7. ^ Microsoft Office XP Developer: Constant Names
嘴苦口臭是什么原因造成的 卡介苗是预防什么的 女生的隐私部位长什么样 生肖排第六是什么生肖 梦见买手表是什么预兆
每个月月经都提前是什么原因 甜菊糖苷是什么 为什么广州叫羊城 什么是心理学 喷砂是什么意思
bigbang是什么意思 急性胃肠炎用什么药 尿蛋白尿潜血同时出现说明什么 远香近臭什么意思 生肖蛇五行属什么
脾是什么器官 十一月一号是什么星座 吃什么缓解便秘 艾滋病脖子有什么症状 甲胄是什么意思
m是什么单位hcv9jop3ns8r.cn iu是什么意思imcecn.com blossom是什么意思hcv9jop1ns6r.cn 乳腺低回声是什么意思hcv8jop5ns7r.cn 辛字五行属什么hcv8jop9ns0r.cn
左手中指戴戒指什么意思hcv9jop6ns8r.cn kumpoo是什么牌子creativexi.com leep是什么意思hcv8jop4ns3r.cn ideal是什么意思hcv8jop2ns0r.cn 真丝丝绒是什么面料hcv8jop0ns9r.cn
结婚15年是什么婚hcv8jop3ns7r.cn 预拌粉是什么东西hcv8jop8ns8r.cn 肺栓塞有什么症状hcv7jop5ns5r.cn 马英九属什么bfb118.com 什么是华盖cl108k.com
铁补多了有什么副作用hcv7jop9ns0r.cn 无名指戴戒指是什么意思hcv9jop6ns1r.cn d3和ad有什么区别hcv9jop4ns9r.cn 宫颈萎缩意味着什么hcv9jop2ns2r.cn 口若悬河是什么意思0735v.com
百度