Пытаюсь сделать функцию, способную оперировать с различными структурами (на данный момент это struct netlist и struct subcircuit). Можно ли как-нибудь упростить этот код? Typedef тут поможет?
Пока объектов, которым можно сделать add_comment() всего два и достаточно if/else, но дальше ведь будет ещё хуже и кривее. Делать множество фактически дублирующихся функций?
struct comment *
add_comment(struct netlist *n, struct subcircuit *s, int lineno, char *text)
{
struct comment *c = malloc(sizeof(struct comment));
if(c == NULL)
return NULL;
c->lineno = lineno;
c->text = text;
c->next = NULL;
if(n == NULL) {
if(s->comments == NULL)
s->comments = s->last_comment = c;
else {
s->last_comment->next = c;
s->last_comment = c;
}
s->ncomments++;
} else {
if(n->comments == NULL)
n->comments = n->last_comment = c;
else {
n->last_comment->next = c;
n->last_comment = c;
}
n->ncomments++;
}
return c;
}
Естественно, struct netlist и struct subcircuit обе имеют поля comments, last_comment и ncomments.
Функцию вызываю так:
add_comment(curr_netlist, NULL, lineno, "abc");
add_comment(NULL, curr_subcircuit, lineno, "abc");
Си я последний раз видел в институте на первом курсе, если что.