3

I was checking code and I came across the following snippet:

int check(char *a)
{

    (void)(a);//What is this line doing??
    return 0;
}

int main(void) 
{

    char *p;
    p=(char *)malloc(sizeof(char));
    check(p);
    return 0;
}

What is (void)(a); doing?

jwodder
  • 54,758
  • 12
  • 108
  • 124
harmands
  • 1,082
  • 9
  • 24
  • Is that the *whole* content of `check`? It's not really checking anything if that's all it does. Maybe it's incomplete. – user2357112 Apr 22 '14 at 04:37

3 Answers3

6

Some compiler may give a warning if a function parameter is not used in the function, (void)a can silence such warnings.

Another commons way to achieve this is:

int check(char *a)
{
    a = a;
    return 0;
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
4

It's supposed to suppress the compiler warning Unused variable 'a'.

This isn't a standard technique, it depends on the particular compiler in use. It is possible to turn off this warning in the compiler. however some people feel that it is useful information to have the compiler diagnose unused variables, so they use this technique to signal that the variable is intentially unused and they don't want to see a warning.

As glampert suggests, I think it is clearer to use a macro with a name such as UNUSED_VAR, so the reader does not wonder what is going on. That approach also has the advantage that you can define it for various compilers in your header file.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • It *isn't* a standard technique? That goes against my experience. Certainly not everyone uses it, but that hardly makes it non-standard. Where or on which compilers would it not work? – Cody Gray - on strike Apr 22 '14 at 04:38
  • I mean, the C standard doesn't say that this code is guaranteed to suppress that compiler warning. I haven't tried every single compiler in existence plus all compilers that might be published in future, so I can't answer your last question. – M.M Apr 22 '14 at 04:40
1

(void)(a); does exactly nothing, and will be compiled away to nothing.

Its purpose in this case is to show that it's not used, but that is intentional, aditionally it will suppress any compiler warnings which would have stated that the variable is unused.

Casper Beyer
  • 2,203
  • 2
  • 22
  • 35