Taskintro
Declare a constant
Also called constant declaration, named constant, define a constant, const, final, constexpr, readonly, compile-time constant, magic number.
Give a fixed value a name that the program cannot assign again, with const, final, constexpr or readonly. Know which constants the compiler computes, and why a constant object can still change inside.
- Evidence
- Code in 10 languages
Task
"In computer programming, a constant is a value that is not altered by the program during normal execution."1 A named constant gives the value a name, such as SECONDS_PER_DAY, so the program does not repeat a bare number such as 86400.
The function seconds_in(days) returns the number of seconds in days days of 24 hours. It declares four named constants: 60 seconds in a minute, 60 minutes in an hour, 24 hours in a day, and the seconds in a day, which the program computes from the other three. The argument is from 0 to 1000000, so the result can be larger than a 32-bit integer.
Solutions
| Language | Declaration | Checked |
|---|---|---|
| Python | SECONDS_PER_DAY: Final = ... |
by a type checker, not when the program runs |
| JavaScript | const SECONDS_PER_DAY = ... |
when the program runs |
| TypeScript | const SECONDS_PER_DAY = ... |
by the compiler |
| Java | static final long SECONDS_PER_DAY = ... |
by the compiler |
| C# | const long SecondsPerDay = ... |
by the compiler |
| Go | const SecondsPerDay = ... |
by the compiler |
| Rust | const SECONDS_PER_DAY: i64 = ... |
by the compiler |
| C | enum { SECONDS_PER_DAY = ... } |
by the compiler |
| C++ | constexpr long long seconds_per_day = ... |
by the compiler |
| Bash | readonly SECONDS_PER_DAY=... |
when the program runs |
- Python. Python has no constants. A name in upper case is a convention, and
typing.Finaltells a type checker: "Final names cannot be reassigned in any scope."2 But "There is no runtime checking of these properties."2 - JavaScript and TypeScript.
constmakes a binding that gets no new value. "The value of a constant can't be changed through reassignment using the assignment operator, but if a constant is an object, its properties can be added, updated, or removed."3 - Java. "A final variable may only be assigned to once."4 A
static finalfield of a primitive type orStringwith a constant expression is a constant variable: "A constant variable is a final variable of primitive type or type String that is initialized with a constant expression"4. - C#. "Constant fields and locals aren't variables and can't be modified."5 The value of a
constmust be known at compile time. For a value that the program computes when it runs, C# hasreadonlyfields. - Go. "A constant declaration binds a list of identifiers (the names of the constants) to the values of a list of constant expressions."6 The constants of the solution have no type. "An untyped constant has a default type which is the type to which the constant is implicitly converted in contexts where a typed value is required"6, so
SecondsPerDaytakes the typeint64indays * SecondsPerDay. - Rust. "Constants must be explicitly typed."7 A constant has no fixed place in memory: "Constants are essentially inlined wherever they are used, meaning that they are copied directly into the relevant context when used."7
- C. A
constvariable is read-only, but it is not a constant expression: "unlike in C++, expressions of const-qualified type in C are not constant expressions; they may not be used as case labels or to initialize static and thread storage duration objects"8. So the solution uses the names of anenum, which are integer constant expressions.#defineis the other common way. - C++. "The constexpr specifier declares that it is possible to evaluate the value of the entities at compile time."9 The solution checks the value with
static_assert(seconds_per_day == 86400), which fails at compile time if the value is wrong. - Bash.
readonlyordeclare -rmarks a name. "These names cannot then be assigned values by subsequent assignment statements or unset."10
Edge cases
- Zero days. The result is 0.
- Past 32 bits. 24855 days give 2147472000 seconds, which still fits in a 32-bit signed integer. 24856 days give 2147558400, which does not. The solutions use 64-bit types for the argument and the result.
- A large argument. 1000000 days give 86400000000 seconds.
Pitfalls
- A constant object can still change.
const,finalandFinalstop a new assignment to the name, but not a change to the object that the name refers to. In Python, the name is not checked at all when the program runs:
This code runs but gives a wrong answer on purpose.
from typing import Final
WEEKDAYS: Final = ["Mon", "Tue", "Wed", "Thu", "Fri"]
WEEKDAYS.append("Sat")
print(len(WEEKDAYS))
WEEKDAYS = []
print(WEEKDAYS)
6
[]
A type checker reports the second assignment, but not the append. For a constant collection, use a type that cannot change, such as a tuple or a frozenset:
from typing import Final
WEEKDAYS: Final = ("Mon", "Tue", "Wed", "Thu", "Fri")
try:
WEEKDAYS.append("Sat")
except AttributeError:
print("a tuple has no append")
print(len(WEEKDAYS))
a tuple has no append
5
In JavaScript, "The Object.freeze() static method freezes an object."11 In Java, List.of makes a list that cannot change, and a final field can refer to it.
- Overflow in the constant expression. In C,
24 * 60 * 60 * 1000has the typeint. A larger product can overflow before it reaches along longvariable. Write one operand as1000LL. - A change through a pointer in C. "Any attempt to modify an object whose type is const-qualified results in undefined behavior."8 A cast that removes
constdoes not make the change safe. - A copied constant. C#, Rust and Java copy the value of a compile-time constant into the code that uses it. If a library changes a public
const, code that was compiled against the old library keeps the old value until it is compiled again.
Related tasks
- Constant: constants as a concept, and the kinds of constants.
- Declare a variable: a name whose value can change.
- Immutability: values that cannot change, as opposed to names that cannot get a new value.
- Single assignment: names that get one value, in all code.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/declare-a-constant/.
from typing import Final
# Final tells a type checker that the name gets no new value. Python itself
# does not check it, and the upper case name is the convention for a
# constant.
SECONDS_PER_MINUTE: Final = 60
MINUTES_PER_HOUR: Final = 60
HOURS_PER_DAY: Final = 24
SECONDS_PER_DAY: Final = SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY
def seconds_in(days: int) -> int:
"""Return the number of seconds in days days of 24 hours."""
return days * SECONDS_PER_DAY
if __name__ == "__main__":
print(seconds_in(7))
test_seconds.py 27 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/declare-a-constant/.
import pytest
from seconds import SECONDS_PER_DAY, seconds_in
CASES = [
("one-day", 1, 86400),
("one-week", 7, 604800),
("one-year", 365, 31536000),
("zero", 0, 0),
("two-days", 2, 172800),
("leap-year", 366, 31622400),
("last-32-bit-day", 24855, 2147472000),
("past-32-bits", 24856, 2147558400),
("million-days", 1000000, 86400000000),
]
@pytest.mark.parametrize(("name", "days", "want"), CASES, ids=[c[0] for c in CASES])
def test_seconds_in(name, days, want):
assert seconds_in(days) == want
def test_seconds_per_day():
assert SECONDS_PER_DAY == 86400
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
#ifndef SECONDS_HPP
#define SECONDS_HPP
// constexpr asks the compiler to compute each value, and static_assert
// checks a value at compile time.
inline constexpr long long seconds_per_minute = 60;
inline constexpr long long minutes_per_hour = 60;
inline constexpr long long hours_per_day = 24;
inline constexpr long long seconds_per_day = seconds_per_minute * minutes_per_hour * hours_per_day;
static_assert(seconds_per_day == 86400);
// Returns the number of seconds in days days of 24 hours.
constexpr long long seconds_in(long long days) {
return days * seconds_per_day;
}
#endif
test_seconds.cpp 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
#include <cstdio>
#include "seconds.hpp"
namespace {
struct test_case {
const char* name;
long long days;
long long want;
};
const test_case cases[] = {
{"one-day", 1, 86400},
{"one-week", 7, 604800},
{"one-year", 365, 31536000},
{"zero", 0, 0},
{"two-days", 2, 172800},
{"leap-year", 366, 31622400},
{"last-32-bit-day", 24855, 2147472000},
{"past-32-bits", 24856, 2147558400LL},
{"million-days", 1000000, 86400000000LL},
};
static_assert(seconds_in(7) == 604800);
} // namespace
int main() {
int failures = 0;
for (const auto& c : cases) {
const long long got = seconds_in(c.days);
if (got != c.want) {
std::printf("FAIL %s: got %lld\n", c.name, got);
++failures;
}
}
if (failures != 0) {
return 1;
}
std::printf("ok\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
/** Named constants for a count of seconds. */
public final class Seconds {
private Seconds() {}
// static final fields of a primitive type, initialized with constant
// expressions, are constant variables: the compiler knows their values.
static final long SECONDS_PER_MINUTE = 60;
static final long MINUTES_PER_HOUR = 60;
static final long HOURS_PER_DAY = 24;
static final long SECONDS_PER_DAY = SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY;
/** Returns the number of seconds in days days of 24 hours. */
public static long secondsIn(long days) {
return days * SECONDS_PER_DAY;
}
public static void main(String[] args) {
System.out.println(secondsIn(7));
}
}
SecondsTest.java 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class SecondsTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("one-day", (long) 1, (long) 86400),
Arguments.of("one-week", (long) 7, (long) 604800),
Arguments.of("one-year", (long) 365, (long) 31536000),
Arguments.of("zero", (long) 0, (long) 0),
Arguments.of("two-days", (long) 2, (long) 172800),
Arguments.of("leap-year", (long) 366, (long) 31622400),
Arguments.of("last-32-bit-day", (long) 24855, (long) 2147472000),
Arguments.of("past-32-bits", (long) 24856, 2147558400L),
Arguments.of("million-days", (long) 1000000, 86400000000L)
);
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void secondsIn(String name, long days, long want) {
assertEquals(want, Seconds.secondsIn(days), name);
}
@Test
void secondsPerDay() {
assertEquals(86400L, Seconds.SECONDS_PER_DAY);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
#include "seconds.h"
long long seconds_in(long long days) {
// SECONDS_PER_DAY has the type int, and C converts it to long long
// before the multiplication.
return days * SECONDS_PER_DAY;
}
seconds.h 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
#ifndef SECONDS_H
#define SECONDS_H
// The names of an enum are integer constant expressions, so one constant
// can use the others. A static const variable cannot do that in C before
// C23.
enum {
SECONDS_PER_MINUTE = 60,
MINUTES_PER_HOUR = 60,
HOURS_PER_DAY = 24,
SECONDS_PER_DAY = SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY,
};
// Returns the number of seconds in days days of 24 hours.
long long seconds_in(long long days);
#endif
test_seconds.c 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
#include "seconds.h"
#include <stdio.h>
#include <stdlib.h>
struct test_case {
const char *name;
long long days;
long long want;
};
static const struct test_case cases[] = {
{"one-day", 1, 86400},
{"one-week", 7, 604800},
{"one-year", 365, 31536000},
{"zero", 0, 0},
{"two-days", 2, 172800},
{"leap-year", 366, 31622400},
{"last-32-bit-day", 24855, 2147472000},
{"past-32-bits", 24856, 2147558400LL},
{"million-days", 1000000, 86400000000LL},
};
int main(void) {
int failures = 0;
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
const struct test_case *c = &cases[i];
long long got = seconds_in(c->days);
if (got != c->want) {
printf("FAIL %s: got %lld\n", c->name, got);
failures++;
}
}
if (SECONDS_PER_DAY != 86400) {
printf("FAIL SECONDS_PER_DAY\n");
failures++;
}
if (failures != 0) {
return EXIT_FAILURE;
}
printf("ok\n");
return EXIT_SUCCESS;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
/// <summary>Named constants for a count of seconds.</summary>
public static class Seconds
{
// A const field gets its value at compile time, and the compiler puts
// the value in each place that uses the name.
public const long SecondsPerMinute = 60;
public const long MinutesPerHour = 60;
public const long HoursPerDay = 24;
public const long SecondsPerDay = SecondsPerMinute * MinutesPerHour * HoursPerDay;
/// <summary>Returns the number of seconds in days days of 24 hours.</summary>
public static long SecondsIn(long days) => days * SecondsPerDay;
}
SecondsTests.cs 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
using Xunit;
public sealed class SecondsTests
{
public static TheoryData<string, long, long> Cases => new()
{
{ "one-day", 1, 86400 },
{ "one-week", 7, 604800 },
{ "one-year", 365, 31536000 },
{ "zero", 0, 0 },
{ "two-days", 2, 172800 },
{ "leap-year", 366, 31622400 },
{ "last-32-bit-day", 24855, 2147472000 },
{ "past-32-bits", 24856, 2147558400 },
{ "million-days", 1000000, 86400000000 },
};
[Theory]
[MemberData(nameof(Cases))]
public void SecondsIn(string name, long days, long want)
{
Assert.NotNull(name);
Assert.Equal(want, Seconds.SecondsIn(days));
}
[Fact]
public void SecondsPerDay()
{
Assert.Equal(86400L, Seconds.SecondsPerDay);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
// const makes a binding that gets no new value. The names in upper case
// are a convention for constants that are known before the program runs.
const SECONDS_PER_MINUTE = 60;
const MINUTES_PER_HOUR = 60;
const HOURS_PER_DAY = 24;
export const SECONDS_PER_DAY = SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY;
/** Returns the number of seconds in days days of 24 hours. */
export function secondsIn(days) {
return days * SECONDS_PER_DAY;
}
seconds.test.js 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { SECONDS_PER_DAY, secondsIn } from "./seconds.js";
const cases = [
["one-day", 1, 86400],
["one-week", 7, 604800],
["one-year", 365, 31536000],
["zero", 0, 0],
["two-days", 2, 172800],
["leap-year", 366, 31622400],
["last-32-bit-day", 24855, 2147472000],
["past-32-bits", 24856, 2147558400],
["million-days", 1000000, 86400000000],
];
for (const [name, days, want] of cases) {
test(name, () => {
assert.equal(secondsIn(days), want);
});
}
test("seconds per day", () => {
assert.equal(SECONDS_PER_DAY, 86400);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
// const makes a binding that gets no new value. The names in upper case
// are a convention for constants that are known before the program runs.
const SECONDS_PER_MINUTE = 60;
const MINUTES_PER_HOUR = 60;
const HOURS_PER_DAY = 24;
export const SECONDS_PER_DAY = SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY;
/** Returns the number of seconds in days days of 24 hours. */
export function secondsIn(days: number): number {
return days * SECONDS_PER_DAY;
}
seconds.test.ts 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { SECONDS_PER_DAY, secondsIn } from "./seconds.ts";
const cases: [string, number, number][] = [
["one-day", 1, 86400],
["one-week", 7, 604800],
["one-year", 365, 31536000],
["zero", 0, 0],
["two-days", 2, 172800],
["leap-year", 366, 31622400],
["last-32-bit-day", 24855, 2147472000],
["past-32-bits", 24856, 2147558400],
["million-days", 1000000, 86400000000],
];
for (const [name, days, want] of cases) {
test(name, () => {
assert.equal(secondsIn(days), want);
});
}
test("seconds per day", () => {
assert.equal(SECONDS_PER_DAY, 86400);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
// Package seconds holds named constants for a count of seconds.
package seconds
// The constants have no type. Each one takes the type int64 where
// SecondsIn uses it.
const (
secondsPerMinute = 60
minutesPerHour = 60
hoursPerDay = 24
SecondsPerDay = secondsPerMinute * minutesPerHour * hoursPerDay
)
// SecondsIn returns the number of seconds in days days of 24 hours.
func SecondsIn(days int64) int64 {
return days * SecondsPerDay
}
seconds_test.go 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
package seconds
import "testing"
var cases = []struct {
name string
days int64
want int64
}{
{"one-day", 1, 86400},
{"one-week", 7, 604800},
{"one-year", 365, 31536000},
{"zero", 0, 0},
{"two-days", 2, 172800},
{"leap-year", 366, 31622400},
{"last-32-bit-day", 24855, 2147472000},
{"past-32-bits", 24856, 2147558400},
{"million-days", 1000000, 86400000000},
}
func TestSecondsIn(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := SecondsIn(c.days); got != c.want {
t.Fatalf("SecondsIn(%d) = %d, want %d", c.days, got, c.want)
}
})
}
}
func TestSecondsPerDay(t *testing.T) {
if SecondsPerDay != 86400 {
t.Fatalf("SecondsPerDay = %d, want 86400", SecondsPerDay)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
// A const item needs a type, and the compiler computes its value. Each use
// of the name gets the value.
const SECONDS_PER_MINUTE: i64 = 60;
const MINUTES_PER_HOUR: i64 = 60;
const HOURS_PER_DAY: i64 = 24;
pub const SECONDS_PER_DAY: i64 = SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY;
/// Returns the number of seconds in `days` days of 24 hours.
pub fn seconds_in(days: i64) -> i64 {
days * SECONDS_PER_DAY
}
tests/seconds_test.rs 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-constant/.
use algo_declare_a_constant::{seconds_in, SECONDS_PER_DAY};
const CASES: &[(&str, i64, i64)] = &[
("one-day", 1, 86400),
("one-week", 7, 604800),
("one-year", 365, 31536000),
("zero", 0, 0),
("two-days", 2, 172800),
("leap-year", 366, 31622400),
("last-32-bit-day", 24855, 2147472000),
("past-32-bits", 24856, 2147558400),
("million-days", 1000000, 86400000000),
];
#[test]
fn cases() {
for &(name, days, want) in CASES {
assert_eq!(seconds_in(days), want, "{name}");
}
}
#[test]
fn seconds_per_day() {
assert_eq!(SECONDS_PER_DAY, 86_400);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/declare-a-constant/.
# readonly marks the names, so a later assignment or unset fails.
readonly SECONDS_PER_MINUTE=60 MINUTES_PER_HOUR=60 HOURS_PER_DAY=24
readonly SECONDS_PER_DAY=$((SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY))
# seconds_in days: print the number of seconds in days days of 24 hours.
seconds_in() {
printf '%d\n' "$(($1 * SECONDS_PER_DAY))"
}
test_seconds.bats 70 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/declare-a-constant/.
setup() {
source "$BATS_TEST_DIRNAME/seconds.sh"
}
@test "one-day" {
run seconds_in 1
[ "$status" -eq 0 ]
[ "$output" = "86400" ]
}
@test "one-week" {
run seconds_in 7
[ "$status" -eq 0 ]
[ "$output" = "604800" ]
}
@test "one-year" {
run seconds_in 365
[ "$status" -eq 0 ]
[ "$output" = "31536000" ]
}
@test "zero" {
run seconds_in 0
[ "$status" -eq 0 ]
[ "$output" = "0" ]
}
@test "two-days" {
run seconds_in 2
[ "$status" -eq 0 ]
[ "$output" = "172800" ]
}
@test "leap-year" {
run seconds_in 366
[ "$status" -eq 0 ]
[ "$output" = "31622400" ]
}
@test "last-32-bit-day" {
run seconds_in 24855
[ "$status" -eq 0 ]
[ "$output" = "2147472000" ]
}
@test "past-32-bits" {
run seconds_in 24856
[ "$status" -eq 0 ]
[ "$output" = "2147558400" ]
}
@test "million-days" {
run seconds_in 1000000
[ "$status" -eq 0 ]
[ "$output" = "86400000000" ]
}
@test "seconds per day" {
[ "$SECONDS_PER_DAY" -eq 86400 ]
}
@test "a constant gets no new value" {
run bash -c 'source "$1"; SECONDS_PER_DAY=1' _ "$BATS_TEST_DIRNAME/seconds.sh"
[ "$status" -ne 0 ]
}
References
- Constant (computer programming), Wikipedia, Introduction
- typing, Support for type hints, Python documentation, typing.Final
- const, MDN Web Docs, Introduction
- Chapter 4, Types, Values, and Variables, The Java Language Specification, Java SE 25, 4.12.4 final Variables
- The const keyword, C# language reference, Introduction
- The Go Programming Language Specification, Constant declarations; Constants
- Constant items, The Rust Reference, items.const
- const type qualifier, cppreference.com (C), Explanation
- constexpr specifier, cppreference.com (C++), Explanation
- Bash Builtin Commands, GNU Bash Reference Manual, declare -r; readonly
- Object.freeze(), MDN Web Docs, Introduction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag F834HP Edit this page History Report an error Markdown