Next: C++
Up: Structures
Previous: Pointers to structures
Contents
Index
Structures can be used within subroutines, both
as return types and within argument lists, in a
straightforward way. For instance, here is a program
to add two fractions:
#include <stdio.h>
typedef struct {
int n, d;
} frac;
frac add_frac(frac, frac);
int main(void) {
frac f1, f2, f3;
f1.n = 1; f1.d = 3;
f2.n = 2; f2.d = 4;
f3 = add_frac(f1, f2);
printf("%d/%d + %d/%d is %d/%d\n", f1.n, f1.d, f2.n, f2.d,
f3.n, f3.d);
return 0;
}
frac add_frac(frac g1, frac g2) {
frac g3;
g3.n = g1.n*g2.d + g2.n*g1.d;
g3.d = g1.d*g2.d;
return g3;
}
Structures can also be used within other structures.