6

I recently found this line of code, but I don't know what the void with () mean. Can someone help me ? Thanks

(void) myFunc();
PacCol
  • 275
  • 2
  • 15
  • You should add more context. What does the rest of the function look like? At least let us know what it returns. – klutt Jun 23 '20 at 20:41

2 Answers2

8

(void) has the form of a cast operation, but casting to void (note: not to void *) is normally not a useful thing to do.

In this context, though, (void) myFunc(); means that myFunc returns a value, and whoever wrote this line of code wanted to throw that value away and did not want the compiler to complain about this, and/or wanted to make it clear to future readers of the code that they were throwing the value away on purpose. In the generated code, (void) myFunc(); has exactly the same effect as myFunc(); with nothing in front.

Due to historic abuses of this notation, some compilers will warn you about not using the value of certain functions (e.g. malloc, read, write) even if you put (void) in front of them, so it's less useful than it used to be.

zwol
  • 135,547
  • 38
  • 252
  • 361
  • 1
    What's meant by "Due to historic abuses of this notation"? – Zircoz Jun 23 '20 at 20:07
  • 3
    @Zircoz There are some C library functions where it's almost always a bug to call them and ignore the return value, but it's relatively common for it to be _inconvenient_ to do something constructive with the return value. So lazy programmers would code e.g. `(void) write(...)` and compiler developers decided to ignore the `(void)` and hit them over the head with "you should have used that value" warnings anyway. If you want to know more about this please ask a new question. – zwol Jun 23 '20 at 20:28
5

myFunc probably returns something. Adding (void) to the the function call, (void)myFunc(), is a way to self-document the code. It means, "I know myFunc returns a value, but I don't care what it is."

Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46