0

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')

sigvardsen
  • 1,531
  • 3
  • 26
  • 44
  • aren't you getting any error like `error: invalid preprocessing directive #DEFINE`, or its just typo? – Dayal rai Jun 26 '13 at 10:51
  • 1
    Why didn't you tell us what the compiler said? You can see it? Surely it's going to be easier if we know what the compiler said? My guess is that the compiler tells you exactly what is wrong. You should learn to read and interpret the error messages that the compiler emits. The fact that you did not include the error suggests that you just ignore the content of the error messages. – David Heffernan Jun 26 '13 at 10:52

4 Answers4

5

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

caf
  • 233,326
  • 40
  • 323
  • 462
5

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
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
2

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;
    }
Lohit
  • 67
  • 2
  • 9
1

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 *);
doptimusprime
  • 9,115
  • 6
  • 52
  • 90