Structs and enums
Enums, structs, arrays of records and a function returning a double.
+ <stdio.h>
e Kind CIRCLE, SQUARE, TRIANGLE
s Shape
kind: Kind
size: f64
f area(s: Shape) f64
k:=0.0
if s.kind == CIRCLE
k = 3.14159
elif s.kind == SQUARE
k = 1
else
k = 0.433
< k * s.size * s.size
f main()
shapes: Shape[3] = {{CIRCLE, 1}, {SQUARE, 2}, {TRIANGLE, 3}}
for i := 0; i < 3; i++
printf("shape %d area %g\n", i, area(shapes[i]))
< 0
#include <stdio.h>
typedef enum {
CIRCLE,
SQUARE,
TRIANGLE
} Kind;
typedef struct Shape Shape;
struct Shape {
Kind kind;
double size;
};
double area(Shape s) {
double k = 0.0;
if (s.kind == CIRCLE) {
k = 3.14159;
} else if (s.kind == SQUARE) {
k = 1;
} else {
k = 0.433;
}
return k * s.size * s.size;
}
int main(void) {
Shape shapes[3] = {{CIRCLE, 1}, {SQUARE, 2}, {TRIANGLE, 3}};
for (int i = 0; i < 3; i++) {
printf("shape %d area %g\n", i, area(shapes[i]));
}
return 0;
}
Output
shape 0 area 3.14159
shape 1 area 4
shape 2 area 3.897
What it shows
records, enums, arrays