MODULE 3 • LESSON 03
Every program you have designed so far has used variables: count, total, mark, fee. In pseudocode you could simply start using a name. C is stricter. Before a variable can be used you must declare it, telling the compiler its name and its data type, so that the right amount of memory can be set aside and the right machine instructions can be chosen for it.
This lesson covers how to declare variables in C, the rules for naming them, the four basic data types (int, float, double and char), how assignment really works (including the surprises of integer division and truncation), constants, and the enum type for giving names to a set of values. You will check identifiers against C’s rules and predict what lands in memory, line by line.
What you will learn
- What a variable is in terms of memory: name, type, value and address.
- How to declare and initialise variables in C, and why uninitialised variables are dangerous.
- The rules for valid identifiers, and the style rules for good ones.
- The data types int, float, double and char: their sizes, what they store and their format specifiers.
- How assignment works, including compound operators, integer division, truncation and casting.
- How to declare constants with #define and const.
- How to declare and use enumerated types with enum.
Part 1: Variables and declarations
A variable is a named location in main memory that holds a value which can change while the program runs. Every variable has four properties: a name (identifier), a data type, a value and an address (where it is in memory). A declaration introduces the name and type:
int count; int length, width; float price = 12.50; char answer = 'Y';
The first line declares one int. The second declares two ints in one statement. The third declares a float and initialises it, and the last declares and initialises a char.
A declaration ends with a semicolon. Several variables of the same type can be declared in one statement, separated by commas. Giving a variable a value in its declaration is called initialising it. In this course, declare variables at the start of a function (or block), before the statements that use them; it keeps programs tidy and is what examiners expect to see.
Why initialise? A local variable that is declared but not initialised does not start at 0. It holds whatever bit pattern was left in that memory location, often called a garbage value. Using it gives unpredictable results that may change from run to run. A good habit (called defensive initialisation in the Intro to C series) is to give every variable a starting value when you declare it.
Part 2: Identifiers
An identifier is the name you give a variable, constant, function or type. C has strict rules:
- It may contain only letters, digits and the underscore (_). No spaces, hyphens or symbols such as $ or %.
- It must start with a letter or an underscore, never a digit.
- It must not be a keyword (reserved word) such as int, float, char, if, while, return or enum.
- C is case-sensitive: total, Total and TOTAL are three different identifiers.
Being legal is not enough. Good identifiers are meaningful (studentAge, not sa), use a consistent style (camelCase such as totalMarks, or snake_case such as total_marks), and keep all capitals for constants (MAX_STUDENTS). Single letters are acceptable only for short-lived counters such as i and j in loops.
Try it 1Identifier checker
Type a name and tap Check, or try the examples. The checker applies C’s rules and also warns about legal names that are poor style.
Part 3: The basic data types
The data type decides how many bytes a variable uses, what kind of value it can hold, and which operations and format specifiers apply. The sizes below are the usual ones on today’s desktop computers (they can differ on other systems, which is why C has the sizeof operator):
| Type | Stores | Usual size | Typical range or precision | printf / scanf | Example |
| int | Whole numbers | 4 bytes | −2 147 483 648 to 2 147 483 647 | %d / %d | int age = 17; |
| float | Real numbers (single precision) | 4 bytes | About 6–7 significant digits | %f / %f | float price = 12.50; |
| double | Real numbers (double precision) | 8 bytes | About 15–16 significant digits | %f / %lf | double dist = 384400.125; |
| char | One character (stored as its code) | 1 byte | −128 to 127 (or 0 to 255) | %c / %c | char grade = 'B'; |
A few points to notice. Real numbers are stored in floating-point form (Module 1), so they are often approximations: 0.1 cannot be stored exactly. A double takes twice the space of a float but is far more precise, which matters for scientific and financial calculations. A char holds a single character in single quotes; text such as "Hello" in double quotes is a string, which you will meet with arrays. C also has modifiers such as short, long and unsigned for other ranges, but the four types above are the ones the syllabus requires (plus enum, in Part 7).
Worked example 1: declaring and displaying each type
#include <stdio.h>
int main(void)
{
int age = 17;
float height = 1.68;
double dist = 384400.125;
char grade = 'B';
printf("int %d bytes: %d\n",
(int) sizeof(age), age);
printf("float %d bytes: %.2f\n",
(int) sizeof(height), height);
printf("double %d bytes: %.3f\n",
(int) sizeof(dist), dist);
printf("char %d byte: %c\n",
(int) sizeof(grade), grade);
return 0;
}
Output:
int 4 bytes: 17 float 4 bytes: 1.68 double 8 bytes: 384400.125 char 1 byte: B
Choosing the right type is a design decision. Ask: is it a whole number (int)? Does it have a fractional part (float, or double if you need many significant digits)? Is it one character (char)? Is it one of a small fixed list of named values (enum)? A telephone number or ID such as 0012 is usually stored as text, not int, because leading zeros matter and you never do arithmetic on it.
Part 4: Assignment and arithmetic
In C, = is the assignment operator. total = total + mark; means: work out the expression on the right using the current values, then store the result in the variable on the left, replacing what was there. The left-hand side must be a variable. It does not mean "equals" in the maths sense; equality is tested with == (Lesson 05).
| Operator | Meaning | Example (a = 17, b = 5) | Result |
| + − * | Add, subtract, multiply | a * b | 85 |
| / | Divide (integer division if both are int) | a / b | 3 |
| % | Remainder (modulus), int only | a % b | 2 |
| += −= *= /= | Compound assignment | a += b (a = a + b) | a becomes 22 |
| ++ −− | Increment, decrement by 1 | a++ | a becomes 18 |
C follows the usual order of operations: brackets first, then * / % (left to right), then + and − (left to right). So 2 + 3 * 4 is 14, and (2 + 3) * 4 is 20. When in doubt, add brackets: they cost nothing and make your intention clear.
Part 5: Type conversion: where the surprises are
Three rules explain almost every "wrong" answer beginners get from C arithmetic:
- Integer division: if both operands of / are int, the result is an int and the fraction is discarded. 7 / 2 is 3, not 3.5.
- Truncation on assignment: storing a real value in an int variable throws away the fractional part. It does not round: 9.99 becomes 9.
- Promotion: if either operand is a float or double, the other is converted and the arithmetic is done in real numbers. 7 / 2.0 is 3.5.
The type of the variable on the left makes no difference to how the right-hand side is worked out. In float g = 7 / 2; the division is done first, with ints, giving 3, and only then is 3 converted to 3.0. To force real division with int variables, use a cast: (float) a / b converts a to float before dividing. You met this in the average programs in Module 2.
Worked example 2: conversions in action
#include <stdio.h>
int main(void)
{
int a = 7, b = 2, whole;
float f;
char c = 'A';
f = a / b;
printf("a / b = %.2f\n", f);
f = (float) a / b;
printf("(float) a / b = %.2f\n", f);
whole = 9.99;
printf("whole = %d\n", whole);
c = c + 2;
printf("c = %c (%d)\n",
c, c);
return 0;
}
Output:
a / b = 3.00 (float) a / b = 3.50 whole = 9 c = C (67)
The last line shows that a char really is a small integer. 'A' is stored as 65 (its ASCII code), so adding 2 gives 67, which prints as C with %c and as 67 with %d.
Try it 2Predict the memory
Choose a program. For each highlighted line, predict what happens, then watch the memory boxes update. The box that has just changed has an orange border.
Worked example 4: choosing types for a real problem
A school canteen program must store: the number of meals sold today, the price of one meal ($18.50), the total takings for the year, the size of drink ordered (small, medium or large), and the first letter of the cashier’s surname. Choose a type and a name for each.
| Data | Name | Type | Reason |
| Meals sold today | mealsSold | int | A count is always whole. |
| Price of one meal | mealPrice | float | Has cents; 6–7 digits is plenty. |
| Total takings for the year | yearTotal | double | Large sums of money keep their cents only with more precision. |
| Drink size | drink | enum Size | One of a fixed list of named values. |
| Cashier initial | initial | char | A single character. |
Notice the reasoning for yearTotal. A float keeps only about 7 significant digits, so a total such as 1 234 567.85 would lose its cents. Professional systems often store money as a whole number of cents in an integer type to avoid rounding problems altogether.
Common errors with variables
- Using a variable before declaring it: the compiler reports that the name is undeclared (a semantic error, Lesson 02).
- Declaring the same name twice in the same block: a redeclaration error.
- Wrong case: declaring Total and then using total. C treats them as different names.
- Missing comma or semicolon:
int a b;is a syntax error. - Double quotes for a char:
char c = "Y";is wrong; a single character uses single quotes. - Expecting rounding: int conversion always truncates towards zero.
Part 6: Constants
A constant is a named value that does not change while the program runs, such as a tax rate or the maximum class size. Using a name instead of typing the number everywhere makes the program easier to read, and if the value ever changes you edit it in one place. C gives you two ways:
| #define | const | |
| Example | #define VAT 0.125 | const float VAT = 0.125; |
| Handled by | The preprocessor (Lesson 02): every VAT is replaced by 0.125 before compiling | The compiler: a read-only variable with a type |
| Has a type? | No, it is text substitution | Yes |
| Semicolon? | No | Yes |
| Trying to change it | Usually a syntax error, because the name has been replaced by a number | Compile error: assignment of read-only variable |
Part 7: Enumerated types with enum
Some values come from a small fixed set: the days of the week, the sizes of a drink, the states of a traffic light, the options on a menu. You could code them as numbers (0 for Monday, 1 for Tuesday…), but then your program is full of unexplained "magic numbers". An enumerated type lets you give each value a name:
enum Day { MON, TUE, WED, THU, FRI };
enum Day today = WED;
The first line creates a new type, enum Day, whose values are the named integer constants MON to FRI. Unless you say otherwise they are numbered from 0: MON is 0, TUE is 1, WED is 2, and so on. The second line declares a variable of that type. You can also choose the values yourself, for example enum Size { SMALL = 250, LARGE = 500 };. Constants without an explicit value continue counting from the previous one.
Why use enum? It makes code self-explaining (if (today == WED) is clearer than if (today == 2)), it groups related constants under one type name, and it works naturally with the switch statement you will meet in Lesson 05. Behind the scenes an enum value is just an int: it prints with %d and can be used in arithmetic. C does not stop you storing other integers in an enum variable, so it is up to you to use it sensibly.
Worked example 3: enum in a program
#include <stdio.h>
enum Day { MON, TUE, WED, THU, FRI };
enum Size { SMALL = 250, LARGE = 500 };
int main(void)
{
enum Day today = WED;
enum Size cup = LARGE;
printf("today = %d\n", today);
if (today == WED)
printf("Mid-week practical\n");
printf("cup = %d ml\n", cup);
return 0;
}
Output:
today = 2 Mid-week practical cup = 500 ml
Try it 3Data type practice
Pick a mode. "Best type" describes a value: choose the best C type. "Value stored" gives an assignment: type exactly what C stores.
Summary
| Idea | Remember |
| Declaration | type name; before use. Initialise to avoid garbage values. |
| Identifiers | Letters, digits, underscore; start with a letter or _; not a keyword; case-sensitive. |
| Types | int (whole), float (real, ~7 digits), double (real, ~15 digits), char (one character, stored as a code). |
| Assignment | = stores the value of the right side in the variable on the left; += ++ are shortcuts. |
| Conversion | int / int drops the fraction; storing a real in an int truncates; cast with (float). |
| Constants | #define (preprocessor) or const (read-only variable). |
| enum | Named integer constants, numbered from 0 unless set. |
Review questions
1. State FOUR rules for a valid C identifier.
Show answer
Only letters, digits and underscores; must begin with a letter or underscore; must not be a keyword; no spaces or special characters. (Also: C is case-sensitive.)
2. Which of these are valid identifiers: total_2, 2total, total-2, Total2, int? Explain each invalid one.
Show answer
Valid: total_2, Total2. 2total starts with a digit; total-2 contains a hyphen (read as minus); int is a keyword.
3. Write declarations for: the number of goals scored, the average speed of a car, a one-letter house name, and the population of the world.
Show answer
int goals; float avgSpeed; char house; and for the world population a double (or long long), because it is larger than the int range: double population;
4. What is stored in each variable? int p = 17 / 5; int q = 17 % 5; float r = 17 / 5; float s = 17 / 5.0;
Show answer
p = 3 (integer division), q = 2 (remainder), r = 3.0 (division done with ints first), s = 3.4.
5. Explain the difference between = and == in C.
Show answer
= is the assignment operator: it stores a value in a variable. == is the equality operator: it compares two values and gives 1 (true) or 0 (false).
6. Explain why an uninitialised variable can cause errors.
Show answer
A local variable that is not initialised holds whatever value was left in that memory location (a garbage value), so calculations using it give unpredictable results.
7. Write an enum for the three traffic light colours and declare a variable set to the colour that means stop. What integer does it hold?
Show answer
enum Light { RED, AMBER, GREEN }; enum Light signal = RED; It holds 0.
8. Give TWO differences between #define and const.
Show answer
#define is handled by the preprocessor as text substitution and has no type or semicolon; const declares a typed, read-only variable handled by the compiler.
Homework
- Write a C program that declares and initialises variables for a student’s name initial, age, height in metres and the distance from home to school in km (to 3 decimal places), then prints them all with suitable labels.
- Predict, then check by running:
int a = 25, b = 4; float c = a / b; float d = (float) a / b; int e = a % b; - Create an enum for the months of the year with JAN = 1. Print the value of DEC. Why might starting at 1 be useful here?
- Find three variable names in an old program of yours that could be more meaningful, and rewrite them.
- Explain, with an example, why a phone number should not be stored in an int.
Mastery quiz: Variables and Data Types
This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.
Mastery quiz: Variables, Data Types and Assignment in C (with enum)
Your course badges: loading saved progress…
View badges
No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.
Saved in this browser on this device. Clearing browser data may remove your badges.
Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.
Exam tips
Specimen Unit 1 Paper 01 (2021), Items 32 and 35. Spotting a valid declaration and an invalid identifier. Check, in order: lower-case keyword, legal first character, only letters, digits and underscores, and a value that suits the type.
Specimen Unit 1 Paper 01 (2021), Items 38 and 44. Data types: which are numeric, and which type gives named integer constants (enum). Remember a Boolean is not one of C’s numeric types in the syllabus list.
CAPE 2019 Unit 1 Paper 02, Question 5, Part C. Correcting errors in a short C fragment, including a faulty declaration. For each error, give the line, what is wrong and the corrected line. A worked answer is in the Go further box.
When a question asks you to "declare variables using appropriate names and data types", choose meaningful names and justify any unusual type (for example double for high precision).
More worked answers are on the CS Solutions page.
Previous: Module 3 • Lesson 02 – How Programs Are Translated and Run. Next: Module 3 • Lesson 04 – Input and Output in C: scanf, printf and Formatted Reports.
Syllabus link: CAPE Computer Science (CXC A19/U2/21), Programming (Unit 1, Module 3). Specific Objective 3: assign values to declared variables (declare variables using appropriate names and data types: int, float, double, char and enum).
Video search terms
Search YouTube for: "C data types int float double char", "C integer division", "C type casting", "C enum tutorial".
Try it 4Quick quiz
Tap an answer. All eight questions are self-checks on this lesson.
Updates
2026/12/01
- Updated the copyright line.
2026/11/24
- First version of the lesson.
© 2026 islandclass.org
