01: // union in struct: uso tipico per rappresentare tipi variabili
02: #include<stdio.h>
03: #include<stdlib.h>
04:
05: // pattern classico: struct con un campo "tipo" (enum) e una union
06: // il campo "tipo" indica quale campo della union e' valido
07: enum tipo_valore { INTERO, REALE, CARATTERE };
08:
09: struct valore
10: {
11: enum tipo_valore tipo;
12: union {
13: int i;
14: float f;
15: char c;
16: } dato;
17: };
18:
19: void stampa(struct valore v)
20: {
21: switch(v.tipo)
22: {
23: case INTERO: printf("intero: %d\n", v.dato.i); break;
24: case REALE: printf("reale: %f\n", v.dato.f); break;
25: case CARATTERE: printf("carattere: %c\n", v.dato.c); break;
26: }
27: }
28:
29: int main(int argc, char **argv){
30:
31: struct valore a = { INTERO, { .i = 42 } };
32: struct valore b = { REALE, { .f = 2.71f } };
33: struct valore c = { CARATTERE, { .c = 'Z' } };
34:
35: stampa(a);
36: stampa(b);
37: stampa(c);
38:
39: return 0;
40: }
41:
Se avete commenti o osservazioni su questa pagina
mandate un messaggio di posta elettronica a bertoƶƶi@ce.unipr.it
mandate un messaggio di posta elettronica a bertoƶƶi@ce.unipr.it