Programming Search⌘K

Taskintro

Declare a variable

Also called variable declaration, declare and initialize a variable, define a variable, create a variable, let, var, local variable, type inference, Variables.

Declare a variable, give it a first value and assign it new values, with a named or an inferred type. Know which languages need a declaration and which make a variable on the first assignment.

Task

The Rosetta Code task asks for the methods of a language for variable declaration, initialization, assignment, datatypes and scope1. A declaration introduces a name. In Go, "A variable declaration creates one or more variables, binds corresponding identifiers to them, and gives each a type and an initial value."2 An initialization gives the first value, and an assignment gives a new value later.

The function total(values) shows all three. It declares a variable result, initializes it to 0, and assigns it a new value once for each value in the list. It returns the sum, and 0 for the empty list. The values and the partial sums fit in a 64-bit signed integer.

Solutions

Each solution declares result inside the function, so the variable is local:

Language Declaration Type
Python result: int = 0 an optional annotation; the first assignment makes the variable
JavaScript let result = 0 no static type
TypeScript let result: number = 0 named, or inferred from 0
Java long result = 0 named; var infers it
C# long result = 0 named; var infers it
Go var result int64 named, with the zero value; := infers it
Rust let mut result: i64 = 0 named, or inferred; mut allows new values
C long long result = 0 named
C++ long long result = 0 named; auto infers it
Bash local -i result=0 no type; -i makes it an integer
  • Python. Python has no declaration statement. The first assignment to a name in a function makes a local variable. An annotation adds a type for tools to check: "Annotation assignment is the combination, in a single statement, of a variable or attribute annotation and an optional assignment statement"3. Python does not check the annotation when the program runs.
  • JavaScript and TypeScript. "The let declaration declares re-assignable, block-scoped local variables, optionally initializing each to a value."4 The loop variable uses const, because it does not change in one pass. TypeScript adds the type number, which it can also infer from 0.
  • Java and C#. The type comes before the name. Both languages also have var: "you can let the compiler infer the type of the variable from the initialization expression"5. The variable still has one static type. In Java, a var declaration without an initializer is an error, for example when "The VariableDeclarator lacks an initializer."6
  • Go. var result int64 declares the variable and gives it the zero value 0. The short form result := int64(0) "is shorthand for a regular variable declaration with initializer expressions but no types"2.
  • Rust. "by default, variables are immutable"7. The solution writes let mut, because result gets a new value on each pass. Without mut, the compiler gives the error "cannot assign twice to immutable variable"7.
  • C and C++. The type comes before the name. A local variable without an initializer has no defined value in C and C++, so the solution writes = 0. C++ also has auto for an inferred type.
  • Bash. local creates a variable "and assign it value"8 that is visible only in the function and the functions it calls. -i makes the variable an integer, so "arithmetic evaluation (see Shell Arithmetic) is performed when the variable is assigned a value"8. In Bash there are no spaces around =.

In Python, a declaration, an annotation and an assignment look like this:

result = 0
for value in [1, 2, 3]:
    result = result + value
print(result)

width: int = 80
height: int
print(width, "height" in globals())
Output
6
80 False

The annotation height: int without a value makes no variable, so the name height is not in the globals.

Edge cases

  • The empty list. The loop does not run, so the result is the first value, 0. This is why the first value matters.
  • One value. The result is that value.
  • Negative values and zeros. [-1, -2, -3] gives -6, and [7, -7] gives 0.
  • Sums past 32 bits. [4000000000, 5000000000] gives 9000000000. A 32-bit int overflows here, so the solutions use 64-bit types: long, int64, i64 and long long.

Pitfalls

  • A typo makes a new variable. In Python, an assignment to a misspelled name makes a second variable, and the program gives a wrong answer with no error:

This code runs but gives a wrong answer on purpose.

result = 0
for value in [1, 2, 3]:
    resutl = result + value
print(result)
Output
0

A language with declarations rejects the typo. In JavaScript modules and strict mode, an assignment to an undeclared name throws ReferenceError. Go, Rust, Java, C# and C reject it at compile time.

  • var in JavaScript. A var variable belongs to the function, not to the block. Also, "var declarations, wherever they occur in a script, are processed before any code within the script is executed."9 Use let and const.
  • No first value in C and C++. long long result; followed by result = result + value reads a value that the program never set. The result can be any number.
  • A global variable in Bash. Without local, an assignment in a function changes a global variable that other functions also see.
  • An unused variable in Go. "A compiler may make it illegal to declare a variable inside a function body if the variable is never used."2 The Go compiler does this, so a declared and unused local variable is an error.

Code

The build runs the native tests of each language in a pinned toolchain.

total.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/declare-a-variable/.


def total(values: list[int]) -> int:
    """Return the sum of values. The function declares the variable result
    with a type annotation, initializes it to 0 and reassigns it once for
    each value."""
    result: int = 0
    for value in values:
        result = result + value
    return result


if __name__ == "__main__":
    print(total([1, 2, 3]))
test_total.py 24 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/declare-a-variable/.

import pytest

from total import total

CASES = [
    ("one-two-three", [1, 2, 3], 6),
    ("four-values", [10, 20, 30, 40], 100),
    ("mixed-signs", [5, -2, 7], 10),
    ("empty", [], 0),
    ("single", [42], 42),
    ("all-negative", [-1, -2, -3], -6),
    ("zeros", [0, 0, 0], 0),
    ("cancel-out", [7, -7], 0),
    ("past-32-bits", [4000000000, 5000000000], 9000000000),
    ("eight-values", [1, 1, 1, 1, 1, 1, 1, 1], 8),
]


@pytest.mark.parametrize(("name", "values", "want"), CASES, ids=[c[0] for c in CASES])
def test_total(name, values, want):
    assert total(values) == want
total.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

#ifndef TOTAL_HPP
#define TOTAL_HPP

#include <vector>

// Returns the sum of values. The variable result has a named type, and
// the loop variable uses auto, so the compiler infers its type.
inline long long total(const std::vector<long long>& values) {
    long long result = 0;
    for (const auto value : values) {
        result = result + value;
    }
    return result;
}

#endif
test_total.cpp 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

#include <cstdio>
#include <vector>

#include "total.hpp"

namespace {

struct test_case {
    const char* name;
    std::vector<long long> values;
    long long want;
};

const test_case cases[] = {
    {"one-two-three", {1, 2, 3}, 6},
    {"four-values", {10, 20, 30, 40}, 100},
    {"mixed-signs", {5, -2, 7}, 10},
    {"empty", {}, 0},
    {"single", {42}, 42},
    {"all-negative", {-1, -2, -3}, -6},
    {"zeros", {0, 0, 0}, 0},
    {"cancel-out", {7, -7}, 0},
    {"past-32-bits", {4000000000LL, 5000000000LL}, 9000000000LL},
    {"eight-values", {1, 1, 1, 1, 1, 1, 1, 1}, 8},
};

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        const long long got = total(c.values);
        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;
}
Total.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

/** Declare a variable, initialize it and reassign it. */
public final class Total {
    private Total() {}

    /**
     * Returns the sum of values. The variable result has the type long,
     * which is named. The loop variable uses var, so the compiler infers
     * its type from the array.
     */
    public static long total(long[] values) {
        long result = 0;
        for (var value : values) {
            result = result + value;
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(total(new long[] {1, 2, 3}));
    }
}
TotalTest.java 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class TotalTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("one-two-three", new long[]{1, 2, 3}, (long) 6),
                Arguments.of("four-values", new long[]{10, 20, 30, 40}, (long) 100),
                Arguments.of("mixed-signs", new long[]{5, -2, 7}, (long) 10),
                Arguments.of("empty", new long[]{}, (long) 0),
                Arguments.of("single", new long[]{42}, (long) 42),
                Arguments.of("all-negative", new long[]{-1, -2, -3}, (long) -6),
                Arguments.of("zeros", new long[]{0, 0, 0}, (long) 0),
                Arguments.of("cancel-out", new long[]{7, -7}, (long) 0),
                Arguments.of("past-32-bits", new long[]{4000000000L, 5000000000L}, 9000000000L),
                Arguments.of("eight-values", new long[]{1, 1, 1, 1, 1, 1, 1, 1}, (long) 8)
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void total(String name, long[] values, long want) {
        assertEquals(want, Total.total(values), name);
    }
}
total.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

#include "total.h"

long long total(const long long *values, size_t n) {
    // A local variable has no start value in C, so give it one.
    long long result = 0;
    for (size_t i = 0; i < n; i++) {
        result = result + values[i];
    }
    return result;
}
total.h 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

#ifndef TOTAL_H
#define TOTAL_H

#include <stddef.h>

// Returns the sum of the n values.
long long total(const long long *values, size_t n);

#endif
test_total.c 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

#include "total.h"

#include <stdio.h>
#include <stdlib.h>

struct test_case {
    const char *name;
    size_t n;
    long long values[8];
    long long want;
};

static const struct test_case cases[] = {
    {"one-two-three", 3, {1, 2, 3}, 6},
    {"four-values", 4, {10, 20, 30, 40}, 100},
    {"mixed-signs", 3, {5, -2, 7}, 10},
    {"empty", 0, {0}, 0},
    {"single", 1, {42}, 42},
    {"all-negative", 3, {-1, -2, -3}, -6},
    {"zeros", 3, {0, 0, 0}, 0},
    {"cancel-out", 2, {7, -7}, 0},
    {"past-32-bits", 2, {4000000000LL, 5000000000LL}, 9000000000LL},
    {"eight-values", 8, {1, 1, 1, 1, 1, 1, 1, 1}, 8},
};

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 = total(c->values, c->n);
        if (got != c->want) {
            printf("FAIL %s: got %lld\n", c->name, got);
            failures++;
        }
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
Totals.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

/// <summary>Declare a variable, initialize it and reassign it.</summary>
public static class Totals
{
    /// <summary>
    /// Returns the sum of values. The variable result has the type long,
    /// which is named. The loop variable uses var, so the compiler infers
    /// its type from the array.
    /// </summary>
    public static long Total(long[] values)
    {
        long result = 0;
        foreach (var value in values)
        {
            result = result + value;
        }
        return result;
    }
}
TotalsTests.cs 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

using System;
using Xunit;

public sealed class TotalsTests
{
    public static TheoryData<string, long[], long> Cases => new()
    {
        { "one-two-three", new long[] { 1, 2, 3 }, 6 },
        { "four-values", new long[] { 10, 20, 30, 40 }, 100 },
        { "mixed-signs", new long[] { 5, -2, 7 }, 10 },
        { "empty", Array.Empty<long>(), 0 },
        { "single", new long[] { 42 }, 42 },
        { "all-negative", new long[] { -1, -2, -3 }, -6 },
        { "zeros", new long[] { 0, 0, 0 }, 0 },
        { "cancel-out", new long[] { 7, -7 }, 0 },
        { "past-32-bits", new long[] { 4000000000, 5000000000 }, 9000000000 },
        { "eight-values", new long[] { 1, 1, 1, 1, 1, 1, 1, 1 }, 8 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Total(string name, long[] values, long want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Totals.Total(values));
    }
}
total.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

/**
 * Returns the sum of values. let declares a variable that can get a new
 * value; const declares the loop variable, which gets a new binding on each
 * pass.
 */
export function total(values) {
  let result = 0;
  for (const value of values) {
    result = result + value;
  }
  return result;
}
total.test.js 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { total } from "./total.js";

const cases = [
  ["one-two-three", [1, 2, 3], 6],
  ["four-values", [10, 20, 30, 40], 100],
  ["mixed-signs", [5, -2, 7], 10],
  ["empty", [], 0],
  ["single", [42], 42],
  ["all-negative", [-1, -2, -3], -6],
  ["zeros", [0, 0, 0], 0],
  ["cancel-out", [7, -7], 0],
  ["past-32-bits", [4000000000, 5000000000], 9000000000],
  ["eight-values", [1, 1, 1, 1, 1, 1, 1, 1], 8],
];

for (const [name, values, want] of cases) {
  test(name, () => {
    assert.equal(total(values), want);
  });
}
total.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

/**
 * Returns the sum of values. The annotation : number is optional, because
 * the compiler infers the type from the initial value 0.
 */
export function total(values: readonly number[]): number {
  let result: number = 0;
  for (const value of values) {
    result = result + value;
  }
  return result;
}
total.test.ts 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { total } from "./total.ts";

const cases: [string, number[], number][] = [
  ["one-two-three", [1, 2, 3], 6],
  ["four-values", [10, 20, 30, 40], 100],
  ["mixed-signs", [5, -2, 7], 10],
  ["empty", [], 0],
  ["single", [42], 42],
  ["all-negative", [-1, -2, -3], -6],
  ["zeros", [0, 0, 0], 0],
  ["cancel-out", [7, -7], 0],
  ["past-32-bits", [4000000000, 5000000000], 9000000000],
  ["eight-values", [1, 1, 1, 1, 1, 1, 1, 1], 8],
];

for (const [name, values, want] of cases) {
  test(name, () => {
    assert.equal(total(values), want);
  });
}
total.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

// Package total declares a variable, initializes it and reassigns it.
package total

// Total returns the sum of values. The var declaration without a value
// gives result the zero value 0 of its type. The short declaration := of
// the loop variable value takes its type from the slice.
func Total(values []int64) int64 {
	var result int64
	for _, value := range values {
		result = result + value
	}
	return result
}
total_test.go 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

package total

import "testing"

var cases = []struct {
	name   string
	values []int64
	want   int64
}{
	{"one-two-three", []int64{1, 2, 3}, 6},
	{"four-values", []int64{10, 20, 30, 40}, 100},
	{"mixed-signs", []int64{5, -2, 7}, 10},
	{"empty", []int64{}, 0},
	{"single", []int64{42}, 42},
	{"all-negative", []int64{-1, -2, -3}, -6},
	{"zeros", []int64{0, 0, 0}, 0},
	{"cancel-out", []int64{7, -7}, 0},
	{"past-32-bits", []int64{4000000000, 5000000000}, 9000000000},
	{"eight-values", []int64{1, 1, 1, 1, 1, 1, 1, 1}, 8},
}

func TestTotal(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := Total(c.values); got != c.want {
				t.Fatalf("Total(%v) = %d, want %d", c.values, got, c.want)
			}
		})
	}
}
total.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

/// Returns the sum of `values`. A `let` variable is immutable unless it
/// has `mut`, and `result` gets a new value on each pass, so it needs
/// `mut`. The annotation `: i64` is optional here, because the compiler
/// infers the type from the return type.
pub fn total(values: &[i64]) -> i64 {
    let mut result: i64 = 0;
    for &value in values {
        result = result + value;
    }
    result
}
tests/total_test.rs 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/declare-a-variable/.

use algo_declare_a_variable::total;

#[test]
fn cases() {
    let cases: Vec<(&str, Vec<i64>, i64)> = vec![
        ("one-two-three", vec![1, 2, 3], 6),
        ("four-values", vec![10, 20, 30, 40], 100),
        ("mixed-signs", vec![5, -2, 7], 10),
        ("empty", vec![], 0),
        ("single", vec![42], 42),
        ("all-negative", vec![-1, -2, -3], -6),
        ("zeros", vec![0, 0, 0], 0),
        ("cancel-out", vec![7, -7], 0),
        ("past-32-bits", vec![4000000000, 5000000000], 9000000000),
        ("eight-values", vec![1, 1, 1, 1, 1, 1, 1, 1], 8),
    ];
    for (name, values, want) in cases {
        assert_eq!(total(&values), want, "{name}");
    }
}
total.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/declare-a-variable/.

# total value...: print the sum of the values. local declares the variable
# result in the function, and declare -i gives it the integer attribute, so
# each assignment computes an arithmetic value. Without local, the variable
# is global.
total() {
  local -i result=0
  local value
  for value in "$@"; do
    result=result+value
  done
  printf '%d\n' "$result"
}
test_total.bats 67 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/declare-a-variable/.

setup() {
  source "$BATS_TEST_DIRNAME/total.sh"
}

@test "one-two-three" {
  run total 1 2 3
  [ "$status" -eq 0 ]
  [ "$output" = "6" ]
}

@test "four-values" {
  run total 10 20 30 40
  [ "$status" -eq 0 ]
  [ "$output" = "100" ]
}

@test "mixed-signs" {
  run total 5 -2 7
  [ "$status" -eq 0 ]
  [ "$output" = "10" ]
}

@test "empty" {
  run total 
  [ "$status" -eq 0 ]
  [ "$output" = "0" ]
}

@test "single" {
  run total 42
  [ "$status" -eq 0 ]
  [ "$output" = "42" ]
}

@test "all-negative" {
  run total -1 -2 -3
  [ "$status" -eq 0 ]
  [ "$output" = "-6" ]
}

@test "zeros" {
  run total 0 0 0
  [ "$status" -eq 0 ]
  [ "$output" = "0" ]
}

@test "cancel-out" {
  run total 7 -7
  [ "$status" -eq 0 ]
  [ "$output" = "0" ]
}

@test "past-32-bits" {
  run total 4000000000 5000000000
  [ "$status" -eq 0 ]
  [ "$output" = "9000000000" ]
}

@test "eight-values" {
  run total 1 1 1 1 1 1 1 1
  [ "$status" -eq 0 ]
  [ "$output" = "8" ]
}

References

  1. Variables, Rosetta Code (the RosettaCodeData mirror), Task description
  2. The Go Programming Language Specification, Variable declarations; Short variable declarations
  3. Simple statements, The Python Language Reference, 7.2.2 Annotated assignment statements
  4. let, MDN Web Docs, Introduction
  5. Declaration statements, C# language reference, Implicitly typed local variables
  6. Chapter 14, Blocks, Statements, and Patterns, The Java Language Specification, Java SE 25, 14.4 Local Variable Declarations
  7. Variables and Mutability, The Rust Programming Language, Variables and Mutability
  8. Bash Builtin Commands, GNU Bash Reference Manual, local; declare
  9. var, MDN Web Docs, Hoisting

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source