Home > Software engineering >  Dynamically changing operator in C
Dynamically changing operator in C

Time:01-19

Currently having many codes that only differ in 1 operator (e.g. ,- ,* ,/ ,& ,| ,== , etc... ) Is it possible to combine these into one common function in C with the operator as a parameter ? Thank you.

Example1

   for (int y = 0; y < v3->y; y  )
            {
                for (int x = 0; x < v3->x; x  )
                {
                    v3->num[y][x] = v1->num[y][x]   v2->num[y][x];
                }
            }

Example2

   for (int y = 0; y < v3->y; y  )
            {
                for (int x = 0; x < v3->x; x  )
                {
                    v3->num[y][x] = v1->num[y][x] * v2->num[y][x];
                }
            }

Example3

   for (int y = 0; y < v3->y; y  )
            {
                for (int x = 0; x < v3->x; x  )
                {
                    v3->num[y][x] = v1->num[y][x] | v2->num[y][x];
                }
            }

Not sure if possible, but Expected something like this...

   for (int y = 0; y < v3->y; y  )
            {
                for (int x = 0; x < v3->x; x  )
                {
                    v3->num[y][x] = v1->num[y][x] operator v2->num[y][x];
                }
            }

CodePudding user response:

As PMF mentions in the comments, you can use a macro – either to wrap just the v3 = v1 OP v2 computation, or the entire loop, such as here (godbolt)

// NB: v1, v2, v3 need to be simple identifiers, this macro is not safe otherwise
#define VLOOP(v3, v1, v2, op) \
    for (int y = 0; y < v3->y; y  ) \
    for (int x = 0; x < v3->x; x  ) \
    v3->num[y][x] = v1->num[y][x] op v2->num[y][x]

typedef struct {
    int x;
    int y;
    int **num;
} V;

void compute_sum(V* v3, V* v1, V* v2) {
    VLOOP(v3, v1, v2,  );
}

void compute_product(V* v3, V* v1, V* v2) {
    VLOOP(v3, v1, v2, *);
}

void compute_division(V* v3, V* v1, V* v2) {
    VLOOP(v3, v1, v2, /);
}

// etc...

CodePudding user response:

You can try this:


#define DO_OP(op) for (int y = 0; y < v3->y; y  ) \
            {\
                for (int x = 0; x < v3->x; x  )\
                {\
                    v3->num[y][x] = v1->num[y][x] op v2->num[y][x];\
                }\
            }

This does not reduce the size of the generated code, but the source will be much smoother. Use as

DO_OP(*)
DO_OP(/)
// etc...
  •  Tags:  
  • Related