简体   繁体   中英

Strange pointer casting with void *

We are working on project about Embedded Linux with C and C++ together. I recenty encountered a strange statement in a function:

bool StrangeFunction(void* arg1, void* arg2, void* arg3)
{
    (void)arg1;
    (void)arg2;
    (void)arg3;

    unsigned long keycode = (unsigned long)arg2;

    switch(keycode)
    {
...

I have two question in the code above

  1. What does it mean that (void)arg1; ?
  2. Is it possible and OK to use unsigned long keycode = (unsigned long)arg2;

If you don't mind, i need some explanation and related links explaining the subjects. Thanks.

  1. It is to silence compiler warnings about unused parameters.

  2. It is possible but not portable. If on the given platform an address fits into unsigned long , it's fine. Use uintptr_t on platforms where it is available to make this code portable.

The cast to void is mostly likely used to silence warnings form the compiler about unused variables, see Suppress unused-parameter compiler warnings in C/C++ :

You should use uintptr_t if possible instead of unsigned long , that is unsigned integer type capable of holding a pointer. We can see from the draft C99 standard section 7.18.1.4 Integer types capable of holding object pointers which says:

The following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer:

uintptr_t

The (void)arg1 does nothing, but makes the compiler use the variable. It's a way to have a function that takes parameters that are not used but avoid any "parameter is unused" compiler warnings.

The second thing is used when passing an unsigned long into a function that takes a void * . If you're dealing with C++ anyway, it's likely better to have an overloaded function. This also has the drawback of requiring that a pointer be at least as big as an unsigned long and so it may not work on certain platforms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM