21

Many times I see in open source code that a call to a C function is cast to void.

For example, in the source code for ls (http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/cmd/ls/ls.c) I see the following.

(void) setlocale(LC_ALL, "");

Why is this good practice?

Russell
  • 3,975
  • 7
  • 37
  • 47

1 Answers1

31

It explicitly means you ignore the return value, and did not just forget it.

zneak
  • 134,922
  • 42
  • 253
  • 328
  • 4
    Some static analyzers warn if a return value is silently ignored and don't warn when you explicitly ignore by casting to void. It was more important when we had only error codes and no exceptions ... – Peter G. Oct 22 '10 at 16:25
  • 3
    @Peter G.: This question is tagged C. They still don't have exceptions. – David Thornley Oct 22 '10 at 16:29
  • @David good point! :) Then let's forget about the second sentence of my first commend. – Peter G. Oct 22 '10 at 16:32
  • 2
    Its a way to hide the fact for the static analyzer that you are ignoring that error code that you should have checked; and that in three years some poor slub will have to debug a problem caused by the fact that you did not check the error code. – Martin York Oct 22 '10 at 19:37