Home > Blockchain >  Cannot use unnamed struct literal at expression in latest C?
Cannot use unnamed struct literal at expression in latest C?

Time:08-16

Here is my code:

void f(void)
{
    typedef struct Position {
        int x;
        int y;
    } Position;

    Position p1 = { 10UL, 10UL };
    if (p1 == (Position){10UL, 10UL}) {}
}

gcc gives me this compile error:

t.c: In function ‘f’:
t.c:9:12: error: invalid operands to binary == (have ‘Position’ {aka ‘struct Position’} and ‘Position’ {aka ‘struct Position’})
    9 |     if (p1 == (Position){10UL, 10UL}) {}
      |            ^~

It looks like I cannot use unnamed struct literal in expression? At this document, https://en.cppreference.com/w/c/language/compound_literal, I do not see there is such restriction.

Could you point me what is wrong of using struct literal like the above?

I am using gcc 9.4.0. I can see it supports the following C standards: c11 c17 c18 c1x c2x c89 c90 c99 c9x

CodePudding user response:

The problem has nothing to do with compound literals.

You're getting an error because you're attempting to use the == operator on two structs. The == operator cannot be used to compare two structs.

Section 6.5.9p2 of the C standard describes the constraints on the == and != operators:

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.

And a struct is not a valid operand.

You'll need to check each field of the struct individually.

if (p1.x == 10L && p1.y == 10L)

CodePudding user response:

You are getting an error message because your posted code is violating the constraints of the == operator (§6.5.9 ¶2 of the ISO C11 standard).

You cannot compare two structs directly using the == operator. You can, however, compare all individual members of two structs.

It would not make much sense for C to allow you to compare two structs directly. For example, structs may contain padding bytes. Should the structs compare equal or not if only the paddding bytes are different? And how should the comparison take place if one of the structs contains a union whose members have different sizes? The bytes of which union member would you want to compare?

These ambiguities are probably the reason why the designers of the language chose not to allow you to compare two structs directly.

  •  Tags:  
  • c
  • Related