Variables and types
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.
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, not8,75. - A
charholds a character in single quotes:'A'. Double quotes"A"make a string (topic 9). - A
charis really a small number:'A'is 65 in memory. Lithuanian letters likeąandždon't fit in onechar: 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. averageandAverageare two different names.- Write names without Lithuanian letters: GCC accepts
amžiustoo, but not every tool does. The course code uses English names:age,average. - A name should say what is inside:
average, nota. 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.