Search code examples
cmacrosc-preprocessorpreprocessor-directive

Is it possible to compute factorial value of a proprocessor value during compile time in C?


#define num 7  \\ user can change this
#define size ????  \\I want this value (factorial of num) to be computed during compile time

int array[size][num];

I want to define array globally, but its size is dependent on preprocessor num's value. So I want the value (factorial of num) to be determined at compile time.

Is it possible? if yes, how?


Solution

  • In a separate .h file (for example fc.h):

    #if num == 1
    #define sum 1
    #elif num == 2
    #define sum 2
    #elif num == 3
    #define sum 6
    #elif num == 4
    #define sum 24
    #elif num == 5
    #define sum 120
    #elif num == 6
    #define sum 720
    #elif num == 7
    #define sum 5040
    #elif num == 8
    #define sum 40320
    #elif num == 9
    #define sum 362880
    #else
    #error wrong number
    #endif
    

    Usage

    #define num 7
    #include "fc.h"
    
    int array[sum][num];