62. void pointer and Casting

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

void add_and_print(void *a, void *b, char type) {
    if (a == NULL || b == NULL) 
    {
        printf("Error: Null pointer exception\n");
        return;
    }

    switch (type) 
    {
        case 'i': 
        {
            int sum = *(int*)a + *(int*)b;
            printf("%d\n", sum);
            break;
        }
        case 'f': {
            float sum = *(float*)a + *(float*)b;
            printf("%.1f\n", sum);
            break;
        }
        default: {
            printf("Error: Unsupported type specifier '%c'\n", type);
            break;
        }
    }
}

int main() {
    char type;
    scanf(" %c", &type);

    if (type == 'i') {
        int x, y;
        scanf("%d %d", &x, &y);
        add_and_print(&x, &y, type);
    } else if (type == 'f') {
        float x, y;
        scanf("%f %f", &x, &y);
        add_and_print(&x, &y, type);
    }

    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote