0

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?

KawaiKx
  • 9,558
  • 19
  • 72
  • 111

4 Answers4

3

You cannot compare structs using ==.

You should compare each member of the struct separately.

MByD
  • 135,866
  • 28
  • 264
  • 277
3

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.

Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125
1

c provides no language facilities to do the == comparison of structs

nvuono
  • 3,323
  • 26
  • 27
1

You cannot compare structures. The standard (C11 6.5.9 Equality operators) states:

One of the following shall hold:
- both operands have arithmetic type;
- both operands are pointers to qualified or unqualified versions of compatible types;
- one operand is a pointer to an object type and the other is a pointer to a qualified or unqualified version of void; or
- one operand is a pointer and the other is a null pointer constant.

None of which apply to a struct time, unfortunately. You'll either have to check the fields individually with == and &&, or have a separate unchanging structure that you can compare with memcmp.

Although keep in mind that the latter suggestion may well run afoul of the padding information within structures, so the former is probably the best bet unless you know there is no padding. .

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953