This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Dont get it

Please can someone show me a code fragment using the following code. I think I understand the enum, and the union part. But dont get how the enum works in conjunction with the union part. Every other example I have found uses an integer in place of the enum to save the union type that's presently in use. I have tried to comprehend how this works but simply miss whats going on.

struct taggedunion {
enum {UNKNOWN, INT, LONG, DOUBLE, POINTER} code;
     union {
             int i;
             long l;
             double d;
             void *p;
     } u;
};

Parents
  • "Every other example I have found uses an integer in place of the enum ..."

    I was taking that to mean that you understood the integer versions.

    #include <stdio.h>
    
    struct taggedunion {
        enum {UNKNOWN, INT, LONG, DOUBLE, POINTER} code;
        union {
            int     i;
            long    l;
            double  d;
            void   *p;
        } u;
    };
    
    void print_vr(struct taggedunion *vr /* Ptr to variant record */)
    {
        switch (vr->code) {
        case INT:     printf("i: %d\n",  vr->u.i); break;
        case LONG:    printf("l: %ld\n", vr->u.l); break;
        case DOUBLE:  printf("d: %lf\n", vr->u.d); break;
        case POINTER: printf("p: %p\n",  vr->u.p); break;
        case UNKNOWN:
        default:      printf("Type unknown\n");    break;
        }
    }
    

Reply
  • "Every other example I have found uses an integer in place of the enum ..."

    I was taking that to mean that you understood the integer versions.

    #include <stdio.h>
    
    struct taggedunion {
        enum {UNKNOWN, INT, LONG, DOUBLE, POINTER} code;
        union {
            int     i;
            long    l;
            double  d;
            void   *p;
        } u;
    };
    
    void print_vr(struct taggedunion *vr /* Ptr to variant record */)
    {
        switch (vr->code) {
        case INT:     printf("i: %d\n",  vr->u.i); break;
        case LONG:    printf("l: %ld\n", vr->u.l); break;
        case DOUBLE:  printf("d: %lf\n", vr->u.d); break;
        case POINTER: printf("p: %p\n",  vr->u.p); break;
        case UNKNOWN:
        default:      printf("Type unknown\n");    break;
        }
    }
    

Children
No data