0

Possible Duplicate:
casting unused return values to void
C++ What is the purpose of casting to void?

After downloading and building the GDCM code using CMake, I stumbled upon this:

void error_callback(const char *msg, void *) {
    (void)msg;
    gdcmErrorMacro( "Error in gdcmopenjpeg" << msg );
}

What does the first line do? Never seen something like that. Keep in mind that I told CMake to build using Visual Studio 2010, if that matters.

dario_ramos
  • 7,118
  • 9
  • 61
  • 108

3 Answers3

9

It prevents unused variable warnings. Presumably the macro gdcmErrorMacro() can be #defined as an empty macro and msg would not be referenced in that case.

hmjd
  • 120,187
  • 20
  • 207
  • 252
3

This prevents a compiler warning emitted when a function's formal parameters aren't used in the function.

It is a generally good idea to compile production code with warnings treated as errors, so this looks like an attempt to clear that up before msg was referred to in the macro use.

This could also have been taken care of by simply not naming a formal parameter in the first place -- in fact, that's what I'd do IRL if there is no mention of msg when using the macro:

void error_callback(const char *, void *) {
}
John Dibling
  • 99,718
  • 31
  • 186
  • 324
2

The parameter msg is not used by that function and the compiler will complain (warning) about unused parameters.

The (void)msg; line simply "uses" that parameter (with no effect). This way, the compiler does not generate the warning.

edit: actually, the function uses that parameter, but the macro gdcmErrorMacro could be set (through a compile-defined macro) to expand to... nothing (for example, to an empty do{}while(0); construction, as customary in the Linux kernel.

This way, the compiler will see nothing in the body of the function that makes use of the parameter msg (remember that the compiler sees the preprocessed source file, so the macros are already expanded).

In that case, after preprocessing, the compiler will see:

void error_callback(const char *msg, void *) {
    (void)msg;
    do{ }while(0);
}

and the sole "use" of the parameter msg would be that line (void)msg;.

user1284631
  • 4,446
  • 36
  • 61