Range (computer programming)
In computer science, the term range may refer to one of three things:
- The possible values that may be stored in a variable.
- The upper and lower bounds of an array.
- An alternative to iterator.
Range of a variable
Range of an array
When an array is numerically indexed, its range is the upper and lower bound of the array. Depending on the environment, a warning, a fatal exception, or unpredictable behavior will occur if the program attempts to access an array element that is outside the range. In some programming languages, such as C, arrays have a fixed lower bound and will contain data at each position up to the upper bound. In others, such as PHP, an array may have holes where no element is defined, and therefore an array with a range of 0 to 4 will have up to 5 elements.Range as an alternative to iterator
Another meaning of range in computer science is an alternative to iterator. When used in this sense, range is defined as "a pair of begin/end iterators packed together". It is argued that "Ranges are a superior abstraction" for several reasons, including better safety.In particular, such ranges are supported in C++20, Boost C++ Libraries and the D standard library.
Range as a data type
A data type for ranges can be implemented using generics.Example in C#.
public record Range
Example in Kotlin.
data class Range
Example in PHP.
readonly class Range
Example in Python.
from dataclasses import dataclass
@dataclass
class Range:
start: T
end: T
Rust has a built-in range struct in the standard library in. C++ has a library as well since C++20.
Range as a operator
has the and operators.let heartwarming = "heartwarming!".to_string;
let warm = &heartwarming;
Zig also has the operator.
// To iterate over consecutive integers, use the range syntax.
var sum: usize = 0;
for |i|
As does C#,
string items = ;
string firstThreeItems = items;
F#,
// Outputs:
Kotlin,
for print
and Perl.
for
Python and PHP does not have any range operator but they do have a function.