Reputation: 5166
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
(void)arg1;
?unsigned long keycode = (unsigned long)arg2;
If you don't mind, i need some explanation and related links explaining the subjects. Thanks.
Upvotes: 4
Views: 246
Reputation: 158459
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
Upvotes: 2
Reputation: 15954
It is to silence compiler warnings about unused parameters.
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.
Upvotes: 10
Reputation: 57248
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.
Upvotes: 0