Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is (void)(p) doing here? [duplicate]

Tags:

c

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?

like image 878
harmands Avatar asked Sep 04 '25 04:09

harmands


2 Answers

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;
}
like image 70
Yu Hao Avatar answered Sep 05 '25 21:09

Yu Hao


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.

like image 30
M.M Avatar answered Sep 05 '25 20:09

M.M