Search code examples
c++macrosreadability

C++ macros to convert readable equations into corresponding code


Suppose I have the following code currently:

double P[2][2][10]; 
std::vector<double> b, r, n; 

//
// Assume that 10 doubles are pushed to each vector and
// that P has all its allocated values set.
//    

for(int t=0; t<10; ++t) {
    P[0][0][t] = b[t]*r[t]+n[t];
    P[0][1][t] = b[t]*2.0*r[t]+(1.0-n[t]);
    P[1][0][t] = b[t]*b[t]+r[t]*n[t];
    P[1][1][t] = r[t]+n[t];
}

This is a trivial example to illustrate my question. In real cases, P will often be P[9][9][100] and the equations will be a little more messy. My question is, basically, how can I use macros to make these equations more readable?

In particular, here is a non-working code fragment to illustrate how I would like the solution to this question to look:

#define P(i,j) P[i][j][t]
#define b b[t]
#define r r[t]
#define n n[t]

for(int t=0; t<10; ++t) {
    P(0,0) = b*r+n;
    P(0,1) = b*2.0*r+(1.0-n);
    P(1,0) = b*b+r*n;
    P(1,1) = r+n;
}

There is at least one problem with this code fragment. For example, it will expand the "r" and "n" in the For-loop statement according to the macro definition. But you get the point.

The goal here is to develop a method for entering in equations that can be more easily read and checked for errors. I'm open to non-macro solutions, though it seems to me that macros could be helpful here.


With respect to the non-working code fragment I posted above to illustrate how I imagine a solution might look... is it possible to use macros in such a way that macro substitution occurs only inside the For-loop body? or at least not until after the For-loop statement?


Solution

  • A posible solution is defining all the macros just before the for and then #undef all macros after the for. Example:

    #define P(i,j) P[i][j][t]
    #define b b[t]
    #define r r[t]
    #define n n[t]
    
    for(int t=0; t<10; ++t) {
        P(0,0) = b*r+n;
        P(0,1) = b*2.0*r+(1.0-n);
        P(1,0) = b*b+r*n;
        P(1,1) = r+n;
    }
    
    #undef P
    #undef b
    #undef r
    #undef n
    

    In my opinion, macros are not the best solution for this problem, but I cannot find any other solution.