Skip to main content

  | मौसम…

411 समाचार
Public archive edition · Attributed source reporting with original dates · AI drafts are excluded

411 REFERENCE · Wikibooks

Programming Fundamentals/Constants and Variables

Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.

Overview A constant is a value that cannot be changed by the program during normal execution, in other words, the value is constant. 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, in other words, the value is variable. Discussion Understanding Constants A constant is a data item whose value cannot change during the program’s execution. Thus, as its name implies – the value is constant. A variable is a data item whose value can change during the program’s execution. Thus, as its name implies – the value can vary. Constants are used in two ways. They are: literal constant defined constant A literal constant is a value you type into your program wherever it is needed. Examples include the constants used for initializing a variable and constants used in lines of code: 21 12.34 'A' "Hello world!" false null In addition to literal constants, most textbooks refer to symbolic constants or named constants as a constant represented by a name. Many programming languages use ALL CAPS to define named constants. LanguageExampleC++#define PI 3.14159or const double PI = 3.14159;C#const double PI = 3.14159;Javaconst double PI = 3.14159;JavaScriptconst PI = 3.14159;PythonPI = 3.14159Swiftlet pi = 3.14159 Technically, Python does not support named constants, meaning that it is possible (but never good practice) to change the value of a constant later. There are workarounds for creating constants in Python, but they are beyond the scope of a first-semester textbook. Defining Constants and Variables Named constants must be assigned a value when they are defined. Variables do not have to be assigned initial values. Variables once defined may be assigned a value within the instructions of the program. LanguageExampleC++double value = 3;C#double value = 3;Javadouble value = 3;JavaScriptvar value = 3;let value = 3;Pythonvalue = 3Swiftvar value:Int = 3 Key Terms Constant A data item whose value cannot change during the program’s execution. Variable A data item whose value can change during the program’s execution. References cnx.org: Programming Fundamentals – A Modular Structured Approach using C++