Foundations
Variables
Variables store typed values that later expressions can reuse.
type
Each C variable has a type such as `int` or `double`.
assignment
An assignment stores a new value in an existing variable.
Variables
variables.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int main(void) {
int unitPrice = 12;
int quantity = 3;
int total = unitPrice * quantity;
printf("unit=%d\n", unitPrice);
printf("total=%d\n", total);
return 0;
}
#include <stdio.h>
int main(void) {
int unitPrice = 8;
int quantity = 3;
int total = unitPrice * quantity;
printf("unit=%d\n", unitPrice);
printf("total=%d\n", total);
return 0;
}
#include <stdio.h>
int main(void) {
int unitPrice = 20;
int quantity = 3;
int total = unitPrice * quantity;
printf("unit=%d\n", unitPrice);
printf("total=%d\n", total);
return 0;
}
unitPrice ← 12, quantity ← 3, total ← 36
3int main(void) {4 int unitPrice→ 12 = 12; //@unitPrice=8, 205 int quantity→ 3 = 3;6 int total→ 36 = unitPrice12 * quantity3;78 printf("unit=%d\n", unitPrice12);9 printf("total=%d\n", total36);10 return 0;11}outputunit=12 total=36
unitPrice ← 8, quantity ← 3, total ← 24
3int main(void) {4 int unitPrice→ 8 = 8;5 int quantity→ 3 = 3;6 int total→ 24 = unitPrice8 * quantity3;78 printf("unit=%d\n", unitPrice8);9 printf("total=%d\n", total24);10 return 0;11}outputunit=8 total=24
unitPrice ← 20, quantity ← 3, total ← 60
3int main(void) {4 int unitPrice→ 20 = 20;5 int quantity→ 3 = 3;6 int total→ 60 = unitPrice20 * quantity3;78 printf("unit=%d\n", unitPrice20);9 printf("total=%d\n", total60);10 return 0;11}outputunit=20 total=60
Follow the Total
unitPricestarts at12.quantitystarts at3.total = unitPrice * quantitymultiplies12 * 3.totalbecomes36.- The program prints
unit=12andtotal=36. | unitPrice | quantity | total | | --- | --- | --- | | 8 | 3 | 24 | | 12 | 3 | 36 | | 20 | 3 | 60 |
Exercise: variables.c
Reproduce unit=12 and total=36, then use the pinned unitPrice values 8 and 20 to predict each total.