面试题 - 用C语言实现支持多种数据类型(包括用户自定义类型)的加减计算器(C语言泛型)

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define ASSERT(T) if(T==NULL) return false;
bool addint(int a, int b, int *res) { ASSERT(res); *res = a+b; return true;};
bool addlong(long a, long b, long *res) { ASSERT(res); *res = a+b; return true;};
typedef struct _mytype {
    int m;
}mytype;

bool addmytype(mytype *a, mytype *b, mytype *res) {
    ASSERT(res);
    res->m = a->m + b->m;
    return true;
}

bool adderror() {
    printf("error: unsupported type");
    return false;
}

#define _add(T,a,b, r) add##T(a, b, r)
#define ADD(a,b, r) _Generic((a), \
    int: _add(int, a, b, r), \
    long: _add(long, a, b, r), \
    mytype*: _add(mytype, a, b, r), \
    default: adderror()\
)

int main() {
    int a=1, b=2, c;
    ADD(a,b,&c);
    printf("int 1+2=%d\n", c);

    long a1=3, b1=4, c1;
    ADD(a1, b1, &c1);
    printf("long 3+4=%ld\n", c1);

    mytype a2, b2, c2;
    a2.m = 5;
    b2.m = 6;
    ADD(&a2, &b2, &c2);
    printf("mytype 5+6=%d\n", c2.m);
}

 

_Genric参考:https://blog.csdn.net/qq_37151416/article/details/113203701

posted @ 2022-07-03 09:55  野猪被骑  阅读(49)  评论(0)    收藏  举报