Search code examples
cif-statementcompound-literals

Compound literals in IF statement


I tried this small code to use compound literals in IF statement:

#include<stdio.h>

struct time
{
    int hour;
    int minutes;
    int seconds;
};

int main(void)
{
    struct time testTimes;
    testTimes = (struct time){12,23,34};

    if (testTimes == (struct time){12,23,34})
        printf("%.2i:%.2i:%.2i\n", testTimes.hour, testTimes.minutes, testTimes.seconds);
    else
        printf("try again !\n");
    return 0;
}

It didn't work. it gave following message on compilation:

prac.c:15:16: error: invalid operands to binary == (have ‘struct time’ and ‘struct time’)

Is it not allowed to use compound literals in IF statement or the syntax is not correct?


Solution

  • There's a good reason as to why you cant compare structures using the == operator

    Quoting from C FAQ

    There is no good way for a compiler to implement structure comparison (i.e. to support the == operator for structures) which is consistent with C's low-level flavor. A simple byte-by-byte comparison could founder on random bits present in unused "holes" in the structure (such padding is used to keep the alignment of later fields correct). A field-by-field comparison might require unacceptable amounts of repetitive code for large structures. Any compiler-generated comparison could not be expected to compare pointer fields appropriately in all cases: for example, it's often appropriate to compare char * fields with strcmp rather than ==.

    If you need to compare two structures, you'll have to write your own function to do so, field by field.