├── Makefile ├── README.md └── matrix.c /Makefile: -------------------------------------------------------------------------------- 1 | all: 2 | gcc -Wall -std=c99 -o matrix matrix.c 3 | 4 | clean: 5 | rm -f matrix 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | Sample matrix implementation illustrating object-oriented techniques in C99. 4 | 5 | It is clear that the techniques presented here have not the pretension to 6 | replace C++, but it provides enough to do serious object-oriented 7 | programming: 8 | 9 | * The procedural model using C functions 10 | * The abstract data type model using public interface and private 11 | implementation as well as data and names encapsulation. 12 | * The object-oriented model using (multiple) inheritance and polymorphism 13 | which allows to manipulate different object types through a common 14 | interface. 15 | 16 | ## Further Reading 17 | * [Matrix Mul](https://msdn.microsoft.com/zh-tw/library/hh873134.aspx) 18 | -------------------------------------------------------------------------------- /matrix.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef struct __matrix_impl Matrix; 4 | struct __matrix_impl { 5 | float values[4][4]; 6 | 7 | /* operations */ 8 | bool (*equal)(const Matrix, const Matrix); 9 | Matrix (*mul)(const Matrix, const Matrix); 10 | }; 11 | 12 | static const float epsilon = 1 / 10000.0; 13 | 14 | static bool equal(const Matrix a, const Matrix b) 15 | { 16 | for (int i = 0; i < 4; i++) 17 | for (int j = 0; j < 4; j++) 18 | if (a.values[i][j] + epsilon < b.values[i][j] 19 | || b.values[i][j] + epsilon < a.values[i][j]) 20 | return false; 21 | return true; 22 | } 23 | 24 | static Matrix mul(const Matrix a, const Matrix b) 25 | { 26 | Matrix matrix = { .values = { 27 | { 0, 0, 0, 0, }, 28 | { 0, 0, 0, 0, }, 29 | { 0, 0, 0, 0, }, 30 | { 0, 0, 0, 0, }, 31 | }, 32 | }; 33 | 34 | for (int i = 0; i < 4; i++) 35 | for (int j = 0; j < 4; j++) 36 | for (int k = 0; k < 4; k++) 37 | matrix.values[i][j] += a.values[i][k] * b.values[k][j]; 38 | 39 | return matrix; 40 | } 41 | 42 | int main() 43 | { 44 | Matrix m = { 45 | .equal = equal, 46 | .mul = mul, 47 | .values = { 48 | { 1, 2, 3, 4, }, 49 | { 5, 6, 7, 8, }, 50 | { 1, 2, 3, 4, }, 51 | { 5, 6, 7, 8, }, 52 | }, 53 | }; 54 | 55 | Matrix n = { 56 | .equal = equal, 57 | .mul = mul, 58 | .values = { 59 | { 1, 2, 3, 4, }, 60 | { 5, 6, 7, 8, }, 61 | { 1, 2, 3, 4, }, 62 | { 5, 6, 7, 8, }, 63 | }, 64 | }; 65 | 66 | Matrix o = { .mul = mul, }; 67 | o = o.mul(m, n); 68 | 69 | return m.equal(o, (Matrix) { 70 | .values = { 71 | { 34, 44, 54, 64, }, 72 | { 82, 108, 134, 160, }, 73 | { 34, 44, 54, 64, }, 74 | { 82, 108, 134, 160, }, 75 | }, 76 | }); 77 | } 78 | --------------------------------------------------------------------------------