45 דק׳

השמה ומעקב

הצהרה, אתחול, השמה ועדכון. הסימן = שומר את הערך מימין במשתנה משמאל. טבלת מעקב שורה אחר שורה, ערך שאף אחד לא קבע, והחלפת שני ערכים בעזרת temp.

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

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

Four actions on a variable

The previous lesson created variables. This lesson changes them. There are four different actions:

ActionCodeWhat it does
Declaration (הצהרה)int count;creates the box; the value is not set
Initialization (אתחול)int count = 0;creates the box with a first value
Assignment (השמה)count = 5;replaces the value; the old one is gone
Update (עדכון)count = count + 1;reads the old value and stores a new one

The first two are two ways to create count; a program uses one of them. Prefer the second. The box always holds the value of the most recent assignment.

= stores the value on the right

In C, = is not "equals". It is an action called assignment (השמה): calculate the right side, then store the result in the variable on the left.

#include <stdio.h>
 
int main(void)
{
    int price = 12;
    int quantity = 3;
    int total = 0;
 
    total = price * quantity;
    printf("Total: %d\n", total);
    return 0;
}
Total: 36

Line 9 runs in two steps:

  1. Right side first. Read price and quantity (12 and 3), multiply them, and get one value: 36.
  2. Then store. Put 36 in total. The old value, 0, is gone.

The left side must be a variable. 36 = total; does not build (error C2106).

Right side first: price * quantity becomes 12 * 3, then 36. Then 36 is stored in total and the old 0 disappears.לפתיחה במסך מלא

Updating a variable

count = count + 1;

In math, x = x + 1 has no solution. In C it is the same rule as before: the right side reads the old value of count (say 5), adds 1, and the result (6) is stored back in count. This line is the heart of every counter and every sum in the loops unit.

Tracing a program

To trace a program, you play the computer: run one line at a time and write down the value of every variable after each line. The table you fill in is a trace table (טבלת מעקב): one row per statement, one column per variable.

#include <stdio.h>
 
int main(void)
{
    int reading = 10;
    reading = 14;
    reading = reading + 3;
    reading = reading * 2;
    printf("%d\n", reading);
    return 0;
}
Statementreading
int reading = 10;10
reading = 14;14
reading = reading + 3;17
reading = reading * 2;34
34
Each click runs one line. Watch the box and the trace table change together.לפתיחה במסך מלא

Tracing is what the written exam asks most often: "What does this program print?" Write the table; do not guess.

A value you never set

int total;
total = total + 5;
printf("%d\n", total);

Line 2 reads total before anything was stored in it. Its value is indeterminate (ערך לא מוגדר): whatever bits were in that memory. Visual Studio's default project settings stop the build:

error C4700: uninitialized local variable 'total' used

Other compilers run the program and print a random number. Fix it by giving the variable a value first: int total = 0;.

Swapping two values

Tom's Exercise 2. Trace it on paper before you read on:

#include <stdio.h>
 
int main(void)
{
    int a = 4;
    int b = 7;
    int temp;
 
    temp = a;
    a = b;
    b = temp;
    a = a + b;
    printf("a=%d, b=%d\n", a, b);
    return 0;
}
Afterabtemp
initialization47?
temp = a474
a = b774
b = temp744
a = a + b1144
a=11, b=4

An assignment copies a value. After temp = a, both a and temp hold 4: the source keeps its value. Only the variable on the left of = changes.

Each assignment sends a copy of a value from one box to another. The trace table fills in as the program runs.לפתיחה במסך מלא

Why a swap needs temp

The obvious way to swap two values does not work:

int a = 4;
int b = 7;
a = b;      /* a gets 7 */
b = a;      /* b gets 7 again */

The first assignment writes over a, and the 4 is gone before the second line needs it. Both variables end up 7. A temporary variable (משתנה עזר) keeps a copy first:

temp = a;
a = b;
b = temp;

Key words

EnglishHebrewMeaning
assignmentהשמה=: store the value of the right side in the variable on the left
initializationאתחולthe first value, given in the declaration
updateעדכוןa new value calculated from the old one
statementהוראהone instruction; ends with ;
trace tableטבלת מעקבthe values of all variables after each line
indeterminate valueערך לא מוגדרthe value of a variable nobody set (?)
temporary variableמשתנה עזרkeeps a copy of a value for a moment (temp)
swapהחלפהexchange the values of two variables

Practice

Answers to exercises 1 and 3 (workbook question 29 and Tom's Exercise 13) are on the practice page. Check exercise 2 by running it.