2

From Programming Language Pragmatics, by Scott:

If the programmer wishes to call a subroutine that does return a value, but the value is not needed in this particular case (all that matters is the side effect[s]), then the return value in C can be discarded by “casting” it to void:

foo_index = insert_in_symbol_table(foo);
...
(void) insert_in_symbol_table(bar);

Can I just call such a subroutine which returns a value as if it returned void?

insert_in_symbol_table(bar);  

What syntax or semantics rules do I violate?

Thanks.

Tim
  • 1
  • 141
  • 372
  • 590

3 Answers3

3

You aren't required to put the cast to void in. For example, the printf function returns a value (how many characters were written), but it's rare to see someone catch the return value or cast it to void.

A void cast is often a good idea if you're calling a function specifically for the side effects in a way that's unusual or counterintuitive and you want to explicitly signal to other people reading the code that yes, you know you're ignoring the return value, and that yes, that was intentional.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
1

You don't violate any rules. The reason why you would want to explicitly do that cast is to let the compiler or a static code analyzer know that you're ignoring the return value on purpose else they might complain about a discarded return value. The reason that code analyzers or a compiler might warn you about this is because usually when a function returns something it's considered information that should be checked/processed.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
1

I don't find the void casting very useful. As far as I understand, it's just as good as a comment, and it won't silence warnings from __attribute__((__warn_unused_result__)) functions (a gcc/clang extension).

I've been using an explicit ignore macro that does silence these (or to simply say I'm ignoring a return value).

/*Ignore macro ( NS == your libs namespace) */
#define NS_ign(Expr)  do{__attribute__((__unused__)) __typeof(Expr) NS_ign = Expr; }while(0)

/*example usage*/
#include <stdio.h>
__attribute__((__warn_unused_result__))
int Puts(char const *X) { return puts(X); }

int main()
{
    //puts returns an int -- no harm done if you silently ignore it
    puts("hello world"); 
    /*(void)Puts("hello world");*/  //(void) cast doesn't silence WUR
    NS_ign(Puts("hello world"));    //this does
}
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142