0

假设我有一个结构:

struct location
{
     int x;
     int y;
};

然后我想定义一个无效的位置,以便稍后在程序中使用:

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

但是,当我在我的程序中使用它时,它最终会出现错误:

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

这不会编译。以这种方式使用复合文字不合法吗?我得到错误:

二进制表达式的无效操作数(“struct location”和“struct location”)

4

4 回答 4

5

我在您的代码中看到了很多错误。

  1. #DEFINE- 没有这样的预处理器(使用#define
  2. 您不能使用==运算符比较结构变量
  3. 您的结构没有名称。location是结构变量而不是结构的名称。所以你不能使用struct location my_loc
于 2013-06-26T10:54:12.623 回答
5

您无法将结构与==.

于 2013-06-26T10:51:59.257 回答
2

您无法按照您提到的方式比较 struct 。将代码修改为如下所述。

    struct location my_loc = { 2, 3 };
    if ((my_loc.x == INVALID_LOCATION.INT_MAX) && (my_loc.y == INVALID_LOCATION.INT_MAX))
    {
         return false;
    }
于 2013-06-26T11:26:00.967 回答
1

请不要在宏及其参数中放置空格。

#define INVALID_LOCATION(location) { INT_MAX, INT_MAX }

它不会编译(错误:二进制 == 的操作数无效或错误:'{' 标记之前的预期表达式)

如果你在 C++ 中,那么你可以重载 == 运算符。

在 C 中,您可以定义一个函数,例如

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

进行比较。

使用此功能,您可以实现

int IsInValid location(const struct location *);
于 2013-06-26T10:56:09.007 回答