“动态”使用C中的变量?

时间:2011-05-13 21:24:20

标签: c function replace

嘿那里, 假设我有以下功能:

#define SIZE 100
double a[SIZE];
double b[SIZE];

double a_function(int index1, int index2)
{
    switch(index1)
    {
        case 1:
            return a[1]*a[2]*a[5]*a[3];
        case 2:
            return a[6]*cos(a[77])*exp(a[95]);
        // .............. MUCH MORE CASES 
        // ALWAYS USING ONLY VALUES OF ARRAY a
        case 100:
            return exp(a[20])*sin(a[21]);
    }
}

我希望实现以下目标:index2介于0和SIZE-1之间,并且我希望在每种情况下使用a[ index2 ]“替换”每个b[ index2 ]而不更改开关/案例构造。此外,a和b不能修改,因此它们是只读的!

这方面的简短例子:
  a_function(2, index2) for index2!= {6,77,95} - >返回a[6]*cos(a[77])*exp(a[95]);

a_function(2, 6) - >返回b[6]*cos(a[77])*exp(a[95]);

有关如何做到这一点的任何想法? 也许有一些帮助功能或使用“模板”? 非常感谢提前!

3 个答案:

答案 0 :(得分:4)

我认为你必须制作一个宏才能做到这一点

#define X(n) ((index2==n)?(b[n]):(a[n]))

double a_function(int index1, int index2)
{
   switch(index1)
    {
        case 1:
            return X(1)*X(2)*X(5)*X(3);
        case 2:
            return X(6)*cos(X(77))*exp(X(95));
        ...
        case 100:
           return exp(X(20))*sin(X(21));
   }

}

答案 1 :(得分:2)

听起来像你有

{
    for (int j=0; j<SIZE; ++j) {
        a_function(index1, j);
    }
}

那么为什么不使用

double c[SIZE];

double a_function(double c[], int index1)
{
    switch(index1)
    {
        case 1:
            return c(1)*c(2)*c(5)*c(3);
        ...
    }
}

{
    double c[SIZE];
    for (int i=SIZE; i--; ) {
        c[i] = a[i];
    }

    for (int j=0; j<SIZE; ++j) {
        c[j] = b[j];
        ... = a_function(c, index1);
        c[j] = a[j];
    }
}

PS - 无论你使用什么方法,你的巨型交换机可能更好地实现为函数指针的查找表。

typedef double (*transform_t)(double*);

double transform1(double* c) { return c[1]*c[2]*c[5]*c[3]; }
double transform2(double* c) { return c[6]*cos(c[77])*exp(c[95]); }
...
double transform100(double* c) { return exp(c[20])*sin(c[21]); }

transform_t transforms[100] = {
    transform1,
    transform2,
    ...
    transform100,
};


{
    double c[SIZE];
    for (int i=SIZE; i--; ) {
        c[i] = a[i];
    }

    ...

    for (int j=0; j<SIZE; ++j) {
        c[j] = b[j];
        ... = (transforms[index1])(c);
        c[j] = a[j];
    }
}

更新:我刚注意到“a和b无法修改,因此它们是只读的!”。调整。

更新:添加了替换switch语句的建议。

答案 2 :(得分:0)

以下是:

    #define SIZE 100
     double a[SIZE];
     double b[SIZE];

     double a_function(int index1, int index2)
     {
switch(index1)
{
    double *choice = (index2 != 6)?a:b;          <<< set choice
    case 1:
        return a[1]*a[2]*a[5]*a[3];               
    case 2:
        return choice[6]*cos(a[77])*exp(a[95]);   <<< use choice
    // .............. MUCH MORE CASES 
    // ALWAYS USING ONLY VALUES OF ARRAY a
    case 100:
        return exp(a[20])*sin(a[21]);
}

}