Search code examples
cswitch-statementconditional-compilation

Replace switch/case by #ifdef or something similar


I'm trying to replace the switch/case structure by an other tool doing the same thing but with better performance ( less execution time ... ), I have in mind the #ifdef method but I have no idea how to use it in such situation:

float k_function(float *x,float *y,struct svm_model model)
{
    int i;
    float sum=0.0;
    switch(model.model_kernel_type)  
    {
    case LINEAR :
        return result1;
    case POLY :
        return result2;
    case RBF :
        return result3;
    case SIGMOID :
        return result4;
    default :
        return 0;
    }
}

PS :

typedef   enum   kernel_type   {LINEAR, POLY, RBF, SIGMOID};

Solution

  • As I already commented, I do not believe preprocessor statements are what you are looking for. To use a preprocessor conditional, model.model_kernel_type would need to be a constant defined using a #define statement.

    I do not know the internals of the switch statement, as it could be O(n) or O(1) depending on how the compiler handles it. If you needed to be sure of a O(1) time complexity, you could simply replace your switch statement with a lookup table like so:

    float model_type_results[4] = {result1, result2, result3, result4};
    
    ...
    
    return model_type_results[model.model_kernel_type];