Alternatives to function overloading in C

前端 未结 2 2016
有刺的猬
有刺的猬 2021-01-16 19:57

I\'m looking for an elegant way to avoid re-writing a function, whose implementation is almost the same, but only the signature (the number of input parameters and their dat

2条回答
  •  没有蜡笔的小新
    2021-01-16 20:17

    This we can exploit using array concepts.

    1) Pass all the arguments(values) i.e. double constants as arrays, like this

    double arr[]={a,b,c,h};
    int trial_no; //1 or 2
    bisect_area_tria2(..., &nthr,arr, &S, area_tria2_nthr,trial_no);
    

    There in that function use array reference like this:

    void area_tria2_nb(..., int *nb, double arr[], double *S,int trial_no) {
    
        // change parameter 'nb'
        ...
    if(trial_no==2){
        S = sqrt(s*(s-arr[0])*(s-arr[1])*(s-arr[2]));
    }
    else
          S = 0.5*arr[1]*arr[3];
    }
    

    For 'nb' or 'nthr', simply pass the address of the corresponding variable. This is just the reference, may not be exact for your situation. If any doubt, ask again.

提交回复
热议问题