Question

I'm learning c and this is an exercise in the book 'Head First C' and my code looks the same as the sample but I'm getting the above error.

#include <stdio.h>

typedef enum {
    COUNT,POUNDS,PINTS
}unit_of_measure;

typedef union {
    short count;
    float weight;
    float volume;
}quantity;

typedef struct{
    const char *name;
    const char *country;
    quantity amount;
    unit_of_measure units;
}fruit_order;

void display(fruit_order order)
{
    printf("The order contains ");

    if(order.amount==PINTS) //ERROR HERE
        printf("%2.2f pints of %s\n",order.amount.weight, order.name);

    else if(order.amount==POUNDS){  //ERROR HERE
            printf("%2.2f lbss of %s\n",order.amount.weight, order.name);

    else
            printf("%i %s\n",order.amount.weight, order.name);

}

int main()
{
    fruit_order apples = {"apples","Canada", .amount.count=100, COUNT};

    fruit_order strawberries = {"strawberries","England", .amount.count=100, PINTS};
    fruit_order oj = {"juice","USA", .amount.count=100, PINTS};

    display(apples);
    display(strawberries);
    display(oj);
    return 0;
}

What does this error mean?

Was it helpful?

Solution 2

void display(fruit_order order)
{
    printf("The order contains ");

    if(order.units==PINTS) {
        printf("%2.2f pints of %s\n",order.amount.weight, order.name);
    }
    else if(order.units==POUNDS){  
            printf("%2.2f lbss of %s\n",order.amount.weight, order.name);
    }
    else {
            printf("%i %s\n",order.amount.weight, order.name);
    }
}

units is unit_of_measure, we should use order.units==PINTS; And I recommend we always use {} in if statement to make the code clearer. I just noticed the original code has missing bracket.

OTHER TIPS

You mean:

if (order.units == PINTS)

Otherwise you are trying to compare an enum value with a union type.

It means what it says.

order.amount is a quantity, which is a union. You're comparing that with an enum, which is an int underneath. You can't do that.

Looking at the code I think what you want is to change the left side of the comparison to order.units:

if(order.units==PINTS) 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top