Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement DRY principle in C for looping over matrices

Tags:

c

loops

dry

When dealing with two-dimensional arrays, e.g. matrices you need to visit elements quite often. The straight forward way to do this is by two nested loops:

for( int i=0; i < n; ++i ) {
  for( int j=0; j < m; ++j ) {
     // do something with data[i][j]
  }
}

This code principle then is often copied over and over again throughout the code. How do you solve this to become DRY? I think the only way to solve this is to use a visitor function with function pointers, right?

Edit: To be more constructive, lets assume you have matrix type typedef double** Matrix;.

For C++ this might be solved this way: Loop over matrix elements applying variable function

like image 715
math Avatar asked Apr 22 '16 06:04

math


1 Answers

First job: consider recasting data as a struct representing the matrix, or, failing that, a simple typedef. I'll assume you do the former.

"// do something with data[i][j]" could be a function (a foo say) that takes i, j, and a pointer to the matrix struct as arguments.

Then you only need one function that does the looping: that function takes the function pointer to an appropriate foo, and the matrix struct pointer.

Your job is then to implement the various foos, according to your requirements.

Don't use macros for this: they make debugging difficult, especially if they introduce hard-coded variable names like i and j.

like image 130
Bathsheba Avatar answered Sep 28 '22 00:09

Bathsheba