Вопрос

Let's say I have a struct:

struct location
{
     int x;
     int y;
};

Then I want to define a invalid location for use later in the program:

#define INVALID_LOCATION (struct location){INT_MAX,INT_MAX}

However when I use that in my program, it ends up in an error:

struct location my_loc = { 2, 3 };
if (my_loc == INVALID_LOCATION)
{
     return false;
}

This won't compile. Is it not legal to use compound literals that way? I get the error:

Invalid operands to binary expression ('struct location' and 'struct location')

Это было полезно?

Решение

You can't compare structures for equality with ==.

Другие советы

I saw a lot of error in your code.

  1. #DEFINE - there is no pre-processor like this (use #define)
  2. You can't compare structure variables using == operator
  3. There is no name for your structure. location is a structure variable not the name of structure. So you can't use struct location my_loc

You can not compare struct the way you have mentioned. Modify the code to as below mentioned.

    struct location my_loc = { 2, 3 };
    if ((my_loc.x == INVALID_LOCATION.INT_MAX) && (my_loc.y == INVALID_LOCATION.INT_MAX))
    {
         return false;
    }

Please do not put spaces with macro and its parameter.

#define INVALID_LOCATION(location) { INT_MAX, INT_MAX }

It would not compile (with error: invalid operands to binary == or error: expected expression before '{' token)

If you are in C++, then you can overload == operator.

In C, you can define a function such as

int EqualLocation (const struct location *, const struct location *);

for comparison.

Using this function, you can implement

int IsInValid location(const struct location *);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top