Skip to the task
Layout
Back to classic view

You are looking at lesson 2. Your place is still lesson 9, task 1: Strings.

READTask 1 of 23 · step 1: Variables and types

Variables and types

A variable, four types and their sizes, a constant, names, and why a variable always gets a starting value.

A variable

Topic 1's program always printed the same text. For a program to calculate, it needs somewhere to keep values. That is what variables are: named places in memory.

int study_year = 1;

This line declares a variable: the type int (a whole number), the name study_year and the starting value 1. From then on, the name study_year means the value kept in that place.

study_yearaveragegroup18.75'A' int · 4 Bdouble · 8 Bchar · 1 B 1 byte= 8 bits

Assignment stores a new value, and the old one is gone:

study_year = 2;

In C, = means "store", not "equals". Whether two values are equal is tested with == (topic 3).

Types

The type says what kind of value a variable holds and how much room it takes. Four are enough for this course:

Type What Size Values printf
int a whole number 4 B from −2,147,483,648 to 2,147,483,647 %d
long long a big whole number 8 B up to ±9.2 · 10¹⁸ %lld
double a real number 8 B about 15–16 exact digits %f
char one character 1 B 'A', '7', '\n' %c

These are the sizes with our compilers: MinGW in CLion and GCC on GitHub. The C standard does not fix them exactly, so you find the real size with sizeof (step 3).

  • The fractional part of a real number comes after a dot: 8.75, not 8,75.
  • A char holds a character in single quotes: 'A'. Double quotes "A" make a string (topic 9).
  • A char is really a small number: 'A' is 65 in memory. Lithuanian letters like ą and ž don't fit in one char: in UTF-8 they take 2 bytes each.

A constant

If a value must not change in the program, add const:

const int current_year = 2026;

Trying to change it is a compile error:

main.c:5:18: error: assignment of read-only variable 'current_year'
    5 |     current_year = 2027;
      |                  ^

Names

  • Letters a–z, A–Z, digits and _ are allowed. A name cannot start with a digit.
  • average and Average are two different names.
  • Write names without Lithuanian letters: GCC accepts amžius too, but not every tool does. The course code uses English names: age, average.
  • A name should say what is inside: average, not a. More in topic 4.

Always a starting value

A variable without a starting value (int sum;) holds whatever was in memory at that moment: a random number. The course flags often catch it:

main.c:5:9: error: 'sum' is used uninitialized [-Werror=uninitialized]
    5 |     sum = sum + 5;
      |     ~~~~^~~~~~~~~

But not always, so the habit is simple: declare a variable and give it a value right away.