#define一个常量结构

sig*_*sen 0 c compound-literals

假设我有一个结构:

struct location
{
     int x;
     int y;
};
Run Code Online (Sandbox Code Playgroud)

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

#define INVALID_LOCATION (struct location){INT_MAX,INT_MAX}
Run Code Online (Sandbox Code Playgroud)

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

struct location my_loc = { 2, 3 };
if (my_loc == INVALID_LOCATION)
{
     return false;
}
Run Code Online (Sandbox Code Playgroud)

这不会编译.以这种方式使用复合文字是不合法的吗?我收到错误:

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

caf*_*caf 5

你无法比较结构的相等性==.


Mid*_* MP 5

我在你的代码中看到了很多错误.

  1. #DEFINE- 没有像这样的预处理器(使用#define)
  2. 您无法使用==运算符比较结构变量
  3. 您的结构没有名称.location是结构变量而不是结构名称.所以你不能使用struct location my_loc