90 דק׳

משתנים וטיפוסים

משתנה הוא מקום בזיכרון עם שם, טיפוס וערך. הצהרה, int, double ו־char, משפחות הטיפוסים, unsigned ו־const, הצצה למערכים ומחרוזות, ואיך בוחרים טיפוס ושם.

למצגתלקריאה באתרבאנגלית בלבד

השיעור הזה כתוב באנגלית בלבד.

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 Wh

Four 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

The number 417 travels from the keyboard to the console. Step through: only board_id keeps it.לפתיחה במסך מלא

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:

  1. Remember input: keep a reading that the operator typed.
  2. Keep a result: store voltage * current as power.
  3. 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:

PropertyExampleThe question it answers
NamevoltageHow does the code refer to it?
TypedoubleWhat kind of value can it hold, and what can you do with it?
Value12.5What 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.

Name, type and value. In the last step the value changes from 12.5 to 12.7; the name and the type do not.לפתיחה במסך מלא

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

TypeUse it forExamplesprintfscanf
intwhole counts and IDs417, -3, 0%d%d
doublemeasurements and fractions4.98, -0.25%f%lf
charone 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:

FamilyTypesThis course
Scalar (טיפוסים פשוטים)integers char short int long, signed or unsigned; floating float double long double; _Boolthis unit
Derived (טיפוסים נגזרים)arrays, pointers, functionsarrays in unit 8, functions in unit 7, pointers later
Constructed (טיפוסים מורכבים)struct, union, enumlater

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:

TypeSizeRange
short2 bytes-32,768 to 32,767
int4 bytes-2,147,483,648 to 2,147,483,647
long4 bytessame as int
long long8 bytesabout -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 = 4294967295
Both boxes start at 2 and lose 1 three times. Predict the unsigned box before the last step.לפתיחה במסך מלא

unsigned is for bit patterns and hardware. It does not make a calculation safe.

Floating-point types

TypeWhenscanfLiteral
floatlower precision, about 7 digits%f1.25f
doublethe usual choice, about 15 digits%lf1.25
long doubleextended precision, when available%Lf1.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.10000000000000000555

There 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 65

A 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?

ValueTypeWhy
board ID or sample countinta whole number; you may calculate with it
register bit patternunsigned intnever negative; the hardware needs it
voltage or averagedoublehas a fraction
one command lettercharexactly one character
four sensor readingsint readings[4]a fixed group of values of one type
device labelchar name[20]text, stored as a string
Tom's checkpoint: six values. Decide on paper first, then tap each card to see a declaration.לפתיחה במסך מלא

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 int or return;
  • capital letters matter: voltage and Voltage are 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.

Exercise 1: valid or invalid? Tap a name to check it.לפתיחה במסך מלא

Key words

EnglishHebrewMeaning
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.