s4b3r6 s4b3r6 - 1 month ago 8
C Question

C Enum is all Zeroes

I'm rather confused.

#include "stdio.h"

typedef enum
{
INTEGER,
NUMBER,
FLOAT,
CHAR,
ARRAY,
STRING
} enumType;

typedef struct intType
{
enumType type;
int width;
int value;
} Integer;

typedef struct fltType
{
enumType type;
int width;
double value;
} Float;

Integer make_int(int val)
{
Integer tmp;
tmp.type = INTEGER;
tmp.width = 32;
tmp.value = val;
return tmp;
}

int get_int(Integer val)
{
int tmp = val.value;
return tmp;
}

Float make_float(double val)
{
Float tmp;
tmp.type = FLOAT;
tmp.width = 32;
tmp.value = val;
return tmp;
}

double get_float(Float val)
{
double tmp = val.value;
return tmp;
}

int main(void) {

Integer i = make_int(42);
printf("Type: %d\nWidth: %d\nValue: %d\n", (int)i.type, i.width, get_int(i));

Float f = make_float(42.8);
printf("Type: %d\nWidth: %d\nValue: %f\n", (int)i.type, i.width, get_float(f));

return 1;

}


This should output six lines, where the two "types" differ. INTEGER and FLOAT from the enumType.

Instead...

Type: 0
Width: 32
Value: 42
Type: 0
Width: 32
Value: 42.800000


Both are 0.

Even if I modify the enum, so both numbers are definitely different, it still doesn't work:

typedef enum
{
INTEGER = 0,
NUMBER,
FLOAT = 1,
CHAR,
ARRAY,
STRING
} enumType;


I have no idea what's going wrong.

Answer

Change in the second printf

printf("Type: %d\nWidth: %d\nValue: %f\n", (int)i.type, i.width, get_float(f));

to

printf("Type: %d\nWidth: %d\nValue: %f\n", (int)f.type, f.width, get_float(f));