Search code examples
c++macros

Defining Exponential Preprocessor Macro


I'm planning on competing in a programming competition in a few months, and I want to define some macros to minimize the typing i need to do. Raising a number to a power is common enough to benefit from this I've been told. I only need it to work with integer arguments (though the arguments themselves may be expressions). I've tried a few different variations but I can't get the correct syntax.

/* c is where the result is stored */
#define EXP(a,b,c) c=a; for (int ii=0; ii<(b)-1; c*=(a), ii++);

This works but i can't use EXP(a,b,c) in an expression like function( EXP(a,b,c) ); I'd have to do

int result; 
EXP(a,b,result); 
function(result);

This, I think would work inside expressions but it fails to compile

#define EXP(a,b) int c=a; for (int ii=0; ii<(b)-1; (c)*=(a), i++); c

with: error: expected primary-expression before ‘int’ when used in:

int result = EXP(2,10);

this is my representative function:

int EXP(int base, int power) {
  int result = base;
  for (int ii=0; ii<power-1; ii++)
    result *= base;
  return result;
}

Solution

  • Using a macro function is the wrong tool for the job. Nevertheless, you say you think it would work inside expressions, consider how would that look for the actual compiler once the preprocessor did his work:

    int result = int c=2; for (int ii=0; ii<(10)-1; (c)*=(2), i++); c
    

    No matter how hard you try, you can't do variable definitions nor for loops within an expression.