Skip to content

Instantly share code, notes, and snippets.

@ainar-g
Created October 11, 2017 11:19
Show Gist options
  • Save ainar-g/7e33368b35be77d89f0ef154e935b621 to your computer and use it in GitHub Desktop.
Save ainar-g/7e33368b35be77d89f0ef154e935b621 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
struct float_interface {
void *value;
void (*add) (void *rhsp, void *lhsp);
void (*print) (void *rhsp);
void (*scan) (void *rhsp);
};
void float_interface_add(struct float_interface fi1,
struct float_interface fi2)
{
fi1.add(fi1.value, fi2.value);
}
void float_interface_print(struct float_interface fi1)
{
fi1.print(fi1.value);
}
void float_interface_scan(struct float_interface fi1)
{
fi1.scan(fi1.value);
}
static void float_add(void *rhsp, void *lhsp)
{
float rhs = *(float *)rhsp;
float lhs = *(float *)lhsp;
rhs += lhs;
*(float *)rhsp = rhs;
}
static void float_print(void *rhsp)
{
float rhs = *(float *)rhsp;
printf("%.9f", rhs);
}
static void float_scan(void *rhsp)
{
scanf("%f", (float *)rhsp);
}
struct float_interface new_float(void)
{
float *fp = malloc(sizeof(float));
struct float_interface fi = {
.value = (void *)fp,
.add = float_add,
.print = float_print,
.scan = float_scan,
};
return fi;
}
static void double_add(void *rhsp, void *lhsp)
{
double rhs = *(double *)rhsp;
double lhs = *(double *)lhsp;
rhs += lhs;
*(double *)rhsp = rhs;
}
static void double_print(void *rhsp)
{
double rhs = *(double *)rhsp;
printf("%.9lf", rhs);
}
static void double_scan(void *rhsp)
{
scanf("%lf", (double *)rhsp);
}
struct float_interface new_double(void)
{
double *fp = malloc(sizeof(double));
struct float_interface fi = {
.value = (void *)fp,
.add = double_add,
.print = double_print,
.scan = double_scan,
};
return fi;
}
int main(void)
{
int type = 0;
printf("enter type (0 = float, 1 = double): ");
scanf("%d", &type);
struct float_interface fi1, fi2;
if (type == 0) {
fi1 = new_float();
fi2 = new_float();
} else {
fi1 = new_double();
fi2 = new_double();
}
printf("enter two numbers: ");
float_interface_scan(fi1);
float_interface_scan(fi2);
float_interface_add(fi1, fi2);
printf("sum is: ");
float_interface_print(fi1);
printf("\n");
free(fi1.value);
free(fi2.value);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment