Home > Software design >  why i cant use args as a constant expression in c
why i cant use args as a constant expression in c

Time:01-15

I have this simple code, I want to send a two args to this function, one is "i" and the other is "n", when try to switch "i" in case of equal to 'n' I failed, because he say 'n' is not a constant expression, I read about this problem, I want to find a method to make 'n' is a constant expression. this is the function:

float east_coefficient(int i, int n){
    switch(i){
        case 1:
            return 0;
            break;
        case n:
            return 0;
            break;
        default:
            return 1;
    }
}

and this is the main function:

int main(){
    int i, x;
    const int n = 5;
    x = east_coefficient(i, n);
    cout << x;
}

CodePudding user response:

Function arguments aren't constant expressions. n and i are not initialized in your code. You can make n a template argument:

#include <iostream>

template <int n>
float east_coefficient(int i){
    switch(i){
        case 1:
            return 0;
            break;
        case n:
            return 0;
            break;
        default:
            return 1;
    }
}

int main(){
    constexpr int n = 2;
    auto x = east_coefficient<n>(42);
    std::cout << x;
}
  •  Tags:  
  • Related