带指针的开关盒

时间:2010-12-23 22:29:02

标签: c gcc

  

可能重复:
  Why no switch on pointers?

int main(int argc, char** argv)
{
  void* not_a_pointer = 42;
  switch(not_a_pointer)
  {
    case 42:
      break;
  }

  return 0;
}

error: switch quantity not an integer

如何将指针类型的变量值可移植地用于switch-case?原因是我正在使用的API中的一个回调函数有一个void *参数。

4 个答案:

答案 0 :(得分:4)

尝试转换为intptr_t,这是一个整数类型:

switch((intptr_t)not_a_pointer)

等...

答案 1 :(得分:2)

如果您知道void*实际上并不是指针,请在尝试在case语句中使用它之前将其强制转换回int

答案 2 :(得分:0)

这应该有效:

int main(int argc, char** argv)
{
  void* not_a_pointer = 42;
  switch((int)not_a_pointer)
  {
    case 42:
      break;
  }

  return 0;
}

答案 3 :(得分:0)

如果要将整数传递给传递void *的回调API,则意图是传递整数的地址。请注意,这可能意味着您需要进行动态分配:

int *foo = malloc(sizeof *foo);
*foo = 42;
register_callback(cbfunc, foo);

然后在回调中:

void cbfunc(void *arg)
{
    int *n = arg;

    switch (*n) {
        case 42:
    }

    free(arg);
}

(你可以将整数强制转换为void *并返回,但转换是实现定义的。void *intptr_t / {{1往返uintptr_t往返需要保留值,但反之则不然。无论如何,它都是丑陋的。)。