4

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.

3 Answers 3

10
  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.

Sign up to request clarification or add additional context in comments.

2 Comments

in GCC 4.8.2, why the second line gives error about [-fpermissive]? Because in my knowledge one type is pointer, and the other is not pointer. Or am i missing anything?
@FredrickGauss: According to the GCC doc (gcc.gnu.org/onlinedocs/gcc-4.8.2/gcc/Option-Summary.html), -fpermissive is a C++ option. I don't know about C++. Sorry.
2

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

Comments

0

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.

1 Comment

thank you also. For my second case, we are interested in C only and even if C++, we cannot use another overloaded function at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.