Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Programming Fundamentals/Constants and Variables

From Wikibooks, open books for an open world
<Programming Fundamentals
Thelatest reviewed version waschecked on18 February 2021. There aretemplate/file changes awaiting review.

Overview

[edit |edit source]

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

[edit |edit source]

Understanding Constants

[edit |edit source]

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:

  1. literal constant
  2. 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:

2112.34'A'"Hello world!"falsenull

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.

LanguageExample
C++#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.14159
Swiftlet 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

[edit |edit source]

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.

LanguageExample
C++double value = 3;
C#double value = 3;
Javadouble value = 3;
JavaScriptvar value = 3;let value = 3;
Pythonvalue = 3
Swiftvar value:Int = 3

Key Terms

[edit |edit source]
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

[edit |edit source]
← Data and Operators
Programming Fundamentals
Identifier Names →
Retrieved from "https://en.wikibooks.org/w/index.php?title=Programming_Fundamentals/Constants_and_Variables&oldid=3811290"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp