Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 251
Fredrick Gauss Avatar asked Dec 15 '22 21:12

Fredrick Gauss


2 Answers

  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.

like image 185
undur_gongor Avatar answered Jan 02 '23 19:01

undur_gongor


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

like image 26
Shafik Yaghmour Avatar answered Jan 02 '23 19:01

Shafik Yaghmour