# Variables and Constants

### Variables and Constants

A program works with values. In Zig, values are usually stored in constants or variables.

A constant is declared with `const`:

```zig
const std = @import("std");

pub fn main() void {
    const year = 2026;

    std.debug.print("{d}\n", .{year});
}
```

Run it:

```text
2026
```

The name `year` cannot be changed after it is declared.

A variable is declared with `var`:

```zig
const std = @import("std");

pub fn main() void {
    var count = 1;

    count = count + 1;

    std.debug.print("{d}\n", .{count});
}
```

The output is:

```text
2
```

A variable may change during the execution of the program.

Use `const` unless the value must change. Most names in Zig programs are constants.

The statement:

```zig
count = count + 1;
```

reads the current value of `count`, adds one, and stores the result back into `count`.

This is common enough that Zig provides a shorter form:

```zig
count += 1;
```

The two forms are equivalent.

Variables and constants have types. In many cases Zig can infer the type automatically:

```zig
const number = 10;
```

Here `number` is an integer.

```zig
const pi = 3.14159;
```

Here `pi` is a floating-point value.

The type can also be written explicitly:

```zig
const number: i32 = 10;
```

`i32` means a signed 32-bit integer.

```zig
const distance: f64 = 12.5;
```

`f64` means a 64-bit floating-point value.

A declaration has this general form:

```zig
const name: type = value;
```

or:

```zig
var name: type = value;
```

The type comes after the colon.

The value comes after the equals sign.

A name must be declared before it is used.

This program is wrong:

```zig
const std = @import("std");

pub fn main() void {
    value = 10;
}
```

`value` has not been declared.

Write it this way:

```zig
const std = @import("std");

pub fn main() void {
    const value = 10;

    std.debug.print("{d}\n", .{value});
}
```

A declaration may appear almost anywhere inside a block:

```zig
const std = @import("std");

pub fn main() void {
    const a = 10;

    {
        const b = 20;
        std.debug.print("{d}\n", .{b});
    }

    std.debug.print("{d}\n", .{a});
}
```

The name `b` exists only inside the inner block.

Blocks control lifetime and visibility.

Exercise 1-9. Declare a variable named `total` and add `5` to it.

Exercise 1-10. Declare a constant named `pi` with the value `3.14`.

Exercise 1-11. Change a `const` value after declaration. Read the compiler error.

Exercise 1-12. Declare an `i64` value and print it with `{d}`.

