Taz bisounours-codeur | Code :
- #include <stdio.h>
- #include <string.h>
- enum Type
- {
- INTEGER,
- REAL,
- STRING
- };
- struct Var
- {
- enum Type type;
- union
- {
- int i;
- double f;
- char str[128];
- } data;
- };
- void Var_init_with_integer(struct Var *v, int i)
- {
- v->type = INTEGER;
- v->data.i = i;
- }
- void Var_init_with_real(struct Var *v, double f)
- {
- v->type = REAL;
- v->data.f = f;
- }
- void Var_init_with_string(struct Var *v, const char *s)
- {
- v->type = STRING;
- strncpy(v->data.str, s, sizeof v->data.str);
- v->data.str[ sizeof v->data.str - 1 ] = '\0';
- }
- void Var_print(const struct Var *v)
- {
- switch(v->type)
- {
- case INTEGER:
- printf("Var %d\n", v->data.i);
- break;
- case REAL:
- printf("Var %f\n", v->data.f);
- break;
- case STRING:
- printf("Var %s\n", v->data.str);
- break;
-
- default:
- printf("Var UNKNOW\n" );
-
- }
- }
- int main()
- {
- struct Var v;
- Var_init_with_integer(&v, 42);
- Var_print(&v);
- Var_init_with_real(&v, 69.69);
- Var_print(&v);
- Var_init_with_string(&v, "TazForEver" );
- Var_print(&v);
- }
|
un exemple simple
attention
e.x = ...;
... = e.y;
est indéfini |