Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22077

Is there any way to make a function smartly in C such that it performs different functions in different values of arguments?

$
0
0

😄

I have to create 2 structs namely rectangle and oval, where the rectangle structure contains its length and breadth and the oval structure contains the lengths of its semi-minor and semi-major axes. Then I have to create a union Shape which has the above two structs as its members. I then have to create a common function 'area' which calculates the area of the union(Either the rectangle or the oval on the basis of the arguments passed to the function). I currently handled the above using a menu-driven approach and using switch cases (code attached after the question).

I want to create a smart function which takes the union as a parameter and calculates the area depending on what structure is stored in the union.

CODE

typedef struct rect{
    int l,b;
}r;
typedef struct oval{
    int x,y;
}o;
union shape{
    r r1;
    o o1;
}sh;
void area(int a);
void main()
{
    int ch;
    int a;
    printf(" 1.Area of rect\n 2.Area of oval\n 3.EXIT");
    while(1){
        printf("\nEnter your choice: ");
        scanf("%d",&ch);
        switch(ch)
        {
            case 1:a=0;
                area(a);
                break;
            case 2:a=1;
                area(a);
                break;
            default:printf("BYE\n");
                return;
        }
    }
}
void area(int a)
{
    if(a==0){
        printf("Enter Length and Breadth: ");
        scanf("%d %d",&sh.r1.l,&sh.r1.b);
        int ar=sh.r1.l*sh.r1.b;
        printf("%d",ar);
    }
    else if(a==1){
        printf("Enter x and y of Oval: ");
        scanf("%d %d",&sh.o1.x,&sh.o1.y);
        float ar=sh.o1.x*sh.o1.y;
        printf("%.2f",ar*3.14);
    }
}

Thanks in advance!


Viewing all articles
Browse latest Browse all 22077

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>