Variables and types
A variable is a named place in memory with a type and a value. Declaration, int, double and char, the type families, unsigned and const, a first look at arrays and strings, and how to choose types and names.
The problem for this unit
A battery test station measures a battery pack. The operator types the pack number, the voltage, the current and the test time. The program must keep these readings, calculate the power and the energy, and print a clear receipt:
--- BATTERY TEST ---
Pack: 73
Voltage: 12.50 V
Current: 1.20 A
Duration: 90 s
Power: 15.00 W
Energy: 0.38 WhFour of these numbers come from the operator. Two are calculated. While the program runs, each number needs a place to live. That place is a variable. By the end of this unit you will write the whole program; it needs no conditions and no loops, only variables, arithmetic, input and output.
Where does a value travel?
Look at four lines you will meet again in unit 3:
int board_id;
printf("Enter board ID: ");
scanf("%d", &board_id);
printf("Board: %d\n", board_id);Line 1 creates a place in memory called board_id. Line 3 reads a number from the keyboard and stores it there: &board_id tells scanf the address, where to put the value. Line 4 reads the value back and prints it with %d, the conversion for an int. The value's journey is:
keyboard → scanf → board_id → printf → console
What a variable is
A variable (משתנה) is a named place in memory that holds a value. The program can read the value or replace it. Programs need variables for three jobs:
- Remember input: keep a reading that the operator typed.
- Keep a result: store
voltage * currentaspower. - Track a change: replace an old reading with a new one.
In this course a variable is always drawn as a box. The type (טיפוס) is written above it, the value (ערך) is inside, and the name (שם) is below:
| Property | Example | The question it answers |
|---|---|---|
| Name | voltage | How does the code refer to it? |
| Type | double | What kind of value can it hold, and what can you do with it? |
| Value | 12.5 | What is stored in it right now? |
The value can change while the program runs. The name and the type stay the same. Two more properties, scope and lifetime, come with functions in unit 7.
Declaration
A declaration (הצהרה) creates a variable. It names the type, then the name, and ends with a semicolon:
double voltage;After this line the box exists, but its value is not set. The memory still holds whatever was there before, so the value is garbage. Give the variable a first value when you declare it. That is called initialization (אתחול):
double voltage = 12.5;Three types to start with
| Type | Use it for | Examples | printf | scanf |
|---|---|---|---|---|
int | whole counts and IDs | 417, -3, 0 | %d | %d |
double | measurements and fractions | 4.98, -0.25 | %f | %lf |
char | one character | 'A', '7' | %c | %c |
#include <stdio.h>
int main(void)
{
int board_id = 417;
double voltage = 4.98;
char grade = 'A';
printf("Board: %d\n", board_id);
printf("Voltage: %f\n", voltage);
printf("Voltage: %.2f V\n", voltage);
printf("Grade: %c\n", grade);
return 0;
}Board: 417
Voltage: 4.980000
Voltage: 4.98 V
Grade: A%f prints six decimals. %.2f prints two. Unit 3 explains all the options of printf.
The type families
C groups its types into families:
| Family | Types | This course |
|---|---|---|
| Scalar (טיפוסים פשוטים) | integers char short int long, signed or unsigned; floating float double long double; _Bool | this unit |
| Derived (טיפוסים נגזרים) | arrays, pointers, functions | arrays in unit 8, functions in unit 7, pointers later |
| Constructed (טיפוסים מורכבים) | struct, union, enum | later |
A scalar type holds one value. The others are built from scalar types.
Integer types
All integer types hold whole numbers, with no fraction. They differ in size, and so in their range. These are the sizes in Visual Studio:
| Type | Size | Range |
|---|---|---|
short | 2 bytes | -32,768 to 32,767 |
int | 4 bytes | -2,147,483,648 to 2,147,483,647 |
long | 4 bytes | same as int |
long long | 8 bytes | about -9.2 × 10¹⁸ to 9.2 × 10¹⁸ |
The exact sizes depend on the compiler. The exam formula sheet lists long as 8 bytes, which is true on Linux. Rule for now: use int for counts and IDs, and choose another integer type only for a clear reason, such as a large range or a hardware requirement.
Signed and unsigned
A signed integer (int) holds negative values, zero and positive values: a temperature change, for example. An unsigned integer (unsigned int) holds only zero and positive values: the bits of a hardware register, for example. Print an unsigned int with %u.
An unsigned value cannot go below zero. It wraps around to its largest value:
#include <stdio.h>
int main(void)
{
int change = 2;
unsigned int count = 2;
change = change - 1;
change = change - 1;
change = change - 1;
count = count - 1;
count = count - 1;
count = count - 1;
printf("change = %d\n", change);
printf("count = %u\n", count);
return 0;
}change = -1
count = 4294967295unsigned is for bit patterns and hardware. It does not make a calculation safe.
Floating-point types
| Type | When | scanf | Literal |
|---|---|---|---|
float | lower precision, about 7 digits | %f | 1.25f |
double | the usual choice, about 15 digits | %lf | 1.25 |
long double | extended precision, when available | %Lf | 1.25L |
Use double for measurements: voltage, current, temperature, averages. Most real numbers are stored with a tiny error, because memory holds them in binary. Print enough decimals and you see it:
printf("%.20f\n", 0.1f);
printf("%.20f\n", 0.1);0.10000000149011611938
0.10000000000000000555There is no unsigned double: floating-point types always hold a sign.
Characters
A char holds one character (תו). In memory it is a small number, the character's code. %c prints it as a character and %d prints the code:
char grade = 'A';
printf("%c %d\n", grade, grade);A 65A character goes in single quotes. 'A' (65) and 'a' (97) are different characters. A char holds one character, not a word; a word needs a string.
Constants
const before a declaration makes a constant (קבוע): a value that no line can change. Tom's example is a 10-bit ADC, which turns 0 to 5 V into the codes 0 to 1023:
const double ADC_REFERENCE_V = 5.0;
const int ADC_MAX_CODE = 1023;
voltage = adc_code * ADC_REFERENCE_V / ADC_MAX_CODE;The names explain the numbers in the formula, and no line can change them by mistake. A line like ADC_MAX_CODE = 1000; does not build: Visual Studio reports error C2166. A constant must get its value when it is declared. Write constant names in capital letters.
The exam formula sheet uses #define for the same job: #define ADC_MAX_CODE 1023. You should be able to read both.
A first look at arrays and strings
An array (מערך) keeps several values of one type under one name. Arrays come in unit 8; for now, recognise them:
int readings[4] = {120, 118, 121, 119};
printf("%d\n", readings[0]);
readings[2] = 125;Every element has the same type, the size is fixed, and the indexes start at 0. readings[0] is 120; readings[4] is outside this array.
C has no string type. A string (מחרוזת) is a char array, and the character '\0' marks where the text ends. "SENSOR" has 6 letters, so it needs 7 cells:
char device_name[8] = "SENSOR";Choosing a type
Ask three questions: what values are possible? What will you do with them? What does the hardware or the exam expect?
| Value | Type | Why |
|---|---|---|
| board ID or sample count | int | a whole number; you may calculate with it |
| register bit pattern | unsigned int | never negative; the hardware needs it |
| voltage or average | double | has a fraction |
| one command letter | char | exactly one character |
| four sensor readings | int readings[4] | a fixed group of values of one type |
| device label | char name[20] | text, stored as a string |
Names
The name of a variable is its identifier (מזהה). The rules:
- letters, digits and
_only; - never start with a digit;
- no spaces;
- not a keyword such as
intorreturn; - capital letters matter:
voltageandVoltageare two different names.
Avoid names that start with _; they are reserved in many places. Prefer clear names in snake_case, such as measured_voltage or board_id.
Key words
| English | Hebrew | Meaning |
|---|---|---|
| variable | משתנה | a named place in memory that holds a value |
| identifier | מזהה | the name of a variable in the code |
| data type | טיפוס נתונים | the kind of value a variable holds |
| value | ערך | what is stored in a variable now |
| declaration | הצהרה | creates a variable: type and name |
| initialization | אתחול | gives a variable its first value |
| integer | מספר שלם | a whole number, no fraction (int) |
| signed / unsigned | בעל סימן / ללא סימן | with or without negative values |
| floating point | נקודה צפה | a number with a fraction (double) |
| character | תו | one letter, digit or sign (char) |
| constant | קבוע | a value that cannot change (const) |
| array | מערך | several values of one type under one name |
| string | מחרוזת | text: a char array that ends with '\0' |
Practice
All of Tom's exercises for this unit, with answers, are on the practice page.