Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 36 ยท Basics and Types

Variables, Constants and Assignment

Declare variables and constants in Pascal, understand typed constants, initial values, scope, assignment with :=, type compatibility and the difference between global and local variables.

A variable is a named box in memory that holds a value of one particular type. Pascal asks you to say what is in the box before you use it. That extra step feels slow at first, but it lets the compiler find typos and type mismatches before the program ever runs.

In this lesson you will declare variables and constants, assign values with :=, learn what values variables start with, and see how scope decides where a name is visible. Pascal listings are read-only; the runnable demos are C stand-ins.

Declaring variables

Variables go in a var section, each with a name, a colon and a type:

PASCAL
program Vars;

var
  age: Integer;
  price: Double;
  initial: Char;
  isReady: Boolean;
  name: string;

begin
  age := 29;
  price := 19.99;
  initial := 'K';
  isReady := True;
  name := 'Kim';
  WriteLn(name, ' (', initial, ') is ', age);
end.

Output:

TEXT
Kim (K) is 29

Several names of the same type can share one declaration:

PASCAL
var
  x, y, z: Integer;
  width, height: Double;

The type names you just met (Integer, Double, Char, Boolean, string) are the topics of the next lessons.

Assignment

:= copies the value on the right into the variable on the left. The right side may be any expression of a compatible type:

PASCAL
total := 0;
total := total + 10;      { the old value is read first, then replaced }
average := total / count; { / always gives a real number }

The = sign is only used for comparison and for constant declarations. Writing total = 5 as a statement is a compile error, which prevents an entire family of C-style bugs.

Types must be compatible. You may assign an Integer to a Double (it widens automatically), but not the other way round without a conversion:

PASCAL
var
  i: Integer;
  d: Double;
begin
  d := 7;        { ok }
  i := d;        { error: incompatible types }
  i := Trunc(d); { ok: Trunc drops the fraction }
  i := Round(d); { ok: Round rounds to nearest }
end.

What value does a new variable have?

It depends on where it is declared:

Where Initial value
Global (in the program's var) Zero, empty string, nil, False
Local (inside a procedure or function) Undefined garbage, except for managed types such as strings
Class fields Zero (objects are cleared when created)

Never read a local numeric variable before assigning it. The compiler usually warns you ("Variable does not seem to be initialized"); treat that warning as an error in your head.

Free Pascal and Delphi allow initial values on global variables:

PASCAL
var
  counter: Integer = 100;
  title: string = 'Report';

Delphi 10.3 and later also supports inline variables with var x := 5; inside a block. Free Pascal does not (as of this writing), so this course declares variables in the var section.

Constants

A constant is a name for a value that never changes. It is declared in a const section with =:

PASCAL
const
  MaxPlayers = 4;
  Pi2 = 6.283185;
  Company = 'Acme';
  Separator = '--------';

The compiler infers the type from the value. You can use a constant wherever a literal is allowed, including as the size of an array. Names are PascalCase by convention.

A typed constant states the type explicitly:

PASCAL
const
  Rate: Double = 0.075;
  Limit: Integer = 10;

Whether a typed constant can be modified depends on the {$J} switch and the compiler mode (an old Turbo Pascal habit lets them act like initialized variables). Use plain constants for values that must never change.

You can also build constants from other constants:

PASCAL
const
  Width = 80;
  Height = 25;
  Area = Width * Height;   { evaluated at compile time }

Scope: where a name is visible

flowchart TD
    G["Global variables<br/>(program level)"] --> P["Procedure Calc<br/>local variables"]
    G --> Q["Procedure Show<br/>local variables"]
    P --> N["Nested routine<br/>sees Calc's and global names"]

Figure: a local name is visible only inside its routine and nested routines; globals are visible everywhere below their declaration.

PASCAL
program Scope;

var
  total: Integer;     { global }

procedure Add(n: Integer);
var
  doubled: Integer;   { local }
begin
  doubled := n * 2;
  total := total + doubled;
end;

begin
  total := 1;
  Add(5);
  WriteLn(total);     { 11 }
end.

If a local variable has the same name as a global one, the local one hides the global inside that routine. Prefer parameters and function results over global variables, because globals make code hard to follow and test.

Naming guidelines

  • Use meaningful names: invoiceTotal, not x1.
  • Loop counters may be short (i, j).
  • Booleans read well as questions: isReady, hasError.
  • Since Pascal ignores case, do not rely on Count versus count.

Stand-in: variables, constants, scope

This C program mirrors the Pascal example: a global, a local, a constant and a hidden name. Observe that the local total hides the global one.

C C stand-in: global, local and hidden names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C C stand-in: widening and truncation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which symbol assigns a value to a variable in Pascal?

    Assignment is :=. A plain = compares values or defines constants.
  2. 2. What is the value of a local Integer variable that was never assigned?

    Locals of simple types are not cleared. Global variables are zero-initialized, but locals contain whatever was in memory.
  3. 3. Given i: Integer; d: Double;, which statement needs a conversion function?

    Assigning a real to an integer loses the fraction, so Pascal requires Trunc or Round. Integer to real is automatic.
  4. 4. What happens when a local variable has the same name as a global one?

    Inside the routine the local name shadows the global one; outside it the global is visible again.

Summary

  • Declare variables in var with name: Type; assign with :=.
  • Constants use const and =; typed constants state their type.
  • Globals start zeroed, locals do not; never read an unassigned local.
  • Scope is lexical: locals hide globals of the same name.
  • Reals need Trunc or Round to become integers.

Next: Integer and Real Types