2

I ran across the following line in an example program, and don't know what it is. I imagine it's a function call, but am not sure:

(void) pthread_mutex_init(&bottleneck, &mxattr);    

If it is a function call, why is it preceded with (void)? I've never seen that before. Here's the line in more context:

attr_init(pthread_process, pthread_scope, stacksize);    
(void) pthread_mutex_init(&bottleneck, &mxattr);    
barrier_init(&setup_barrier, (2 * ntables) + 1);    

Thanks for the help. The entire program is from this Solaris whitepaper (Appendix D)

prm.cs1
  • 21
  • 1

4 Answers4

7

It is a normal function call. The (void) part just indicates that the function returns a value and nothing will be done with it. To remove any warnings of about unused return values.

See casting unused return values to void.

Community
  • 1
  • 1
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
  • A cast-to-void does not silence a function declared with `__attribute__((warn_unused_result))`, at least on gcc 4.4.3 on Ubuntu 10.04. – Jack Kelly Sep 03 '10 at 02:38
  • @Jack, in gcc you can disable that using -Wno-unused-result option. –  Sep 03 '10 at 02:50
  • It should be noted that a good portion of C coders (not sure if it's more or less than 50% though) consider casts to `(void)` bad style. – R.. GitHub STOP HELPING ICE Sep 03 '10 at 11:47
  • 1
    @R: Yes, the explicit cast to void tells you that you should immediately check the API documentation to find out what the programmer is deliberately ignoring. After this, you should give the programmer a slap for carrying on even though he may have failed to create the mutex. – JeremyP Sep 03 '10 at 14:39
4

POSIX Threads

The specific call - pthread_mutex_init - returns int. The cast to void is probably done to avoid specific warning about the return value being ignored during either compile time or a static code analysis.

Update: As @Jack Kelly commented on another answer, any good static analysis tool would simply ignore this cast and continue issuing the warning. Static analysis should be controlled through separate specific annotations, not by using language constructs that can affect the compiler output.

Franci Penov
  • 74,861
  • 18
  • 132
  • 169
1

This is a function call with explicit casting of the result to void. This is just a development style to hint both compiler and those who read this code that function call is actually returning something that is intentionally ignored. In this example, pthread_mutex_init function returns integer. Some compilers will give you a warning if you call a function marked with warn_unused_result attribute.

1

Yes it is a function call. The function pthread_mutex_init() initializes a mutex used to prevent multiple threads clobberring some shared resource.

The function returns an int, the (void) is flagging that we are intentionally ignoring the return value. It stops the compiler complaining about unused return values.