Structs
Pass Struct
Passing a struct by value gives a function its own copy of the fields.
by value
The function receives a copy of the struct argument.
compute from fields
The function can read fields from its copy to compute a result.
Pass Struct
pass_struct.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
struct Box {
int width;
int height;
};
int area(struct Box box) {
return box.width * box.height;
}
int main(void) {
int width = 4;
struct Box box = {width, 5};
int result = area(box);
printf("area=%d\n", result);
return 0;
}
#include <stdio.h>
struct Box {
int width;
int height;
};
int area(struct Box box) {
return box.width * box.height;
}
int main(void) {
int width = 6;
struct Box box = {width, 5};
int result = area(box);
printf("area=%d\n", result);
return 0;
}
#include <stdio.h>
struct Box {
int width;
int height;
};
int area(struct Box box) {
return box.width * box.height;
}
int main(void) {
int width = 8;
struct Box box = {width, 5};
int result = area(box);
printf("area=%d\n", result);
return 0;
}
width ← 4, box ← (empty)
12int main(void) {13 int width→ 4 = 4; //@width=6, 814 struct Box box→ (empty) = {width4, 5};15 int result = area(box(empty));int area(struct Box box)
8int area(struct Box box(empty)) {9 return box.width4 * box.height5;10}result ← 20
14 struct Box box = {width, 5};15 int result→ 20 = area(box(empty));1617 printf("area=%d\n", result20);18 return 0;19}outputarea=20
width ← 6, box ← (empty)
12int main(void) {13 int width→ 6 = 6;14 struct Box box→ (empty) = {width6, 5};15 int result = area(box(empty));int area(struct Box box)
8int area(struct Box box(empty)) {9 return box.width6 * box.height5;10}result ← 30
14 struct Box box = {width, 5};15 int result→ 30 = area(box(empty));1617 printf("area=%d\n", result30);18 return 0;19}outputarea=30
width ← 8, box ← (empty)
12int main(void) {13 int width→ 8 = 8;14 struct Box box→ (empty) = {width8, 5};15 int result = area(box(empty));int area(struct Box box)
8int area(struct Box box(empty)) {9 return box.width8 * box.height5;10}result ← 40
14 struct Box box = {width, 5};15 int result→ 40 = area(box(empty));1617 printf("area=%d\n", result40);18 return 0;19}outputarea=40