Pointer switch

Possible duplicate:
Why are there no pointers to 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

How can I use a portable port for a variable value with a pointer type? The reason for this is because one of the callback functions in the API I use has the void * argument.

+3
source share
4 answers

try casting on intptr_twhich is an integer type:

switch((intptr_t)not_a_pointer)

etc...

+4
source

If you know what void*is not really a pointer, return it to intbefore trying to use it in a case statement.

+2
source

:

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

  return 0;
}
0

If you want to pass an integer to the callback API that passes void *, it is assumed that you pass the address of the integer. Note that this may mean that you need to perform dynamic allocation:

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

Then in the callback:

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

    switch (*n) {
        case 42:
    }

    free(arg);
}

(You can force the integer to void *and back, but the conversions are defined according to the implementation. The void *to intptr_t/ uintptr_tto deviation void *is required to preserve the value, but the converse is not so. It's ugly, anyway.).

0
source

Source: https://habr.com/ru/post/1781924/


All Articles