Reputation: 2330
I'm seeing a macro definition like this:
#define ASSERT_VALID_PARAM(param, assertion) { static_cast<void>(param); if (!(assertion)) { throw InvalidParamError(#param, #assertion, __FILE__, __PRETTY_FUNCTION__, __LINE__); } }
I'm not able to figure out the need of static_cast<void>(param)
here.
Any idea on why this is needed?
Upvotes: 1
Views: 1879
Reputation: 46341
This macro is designed to validate a certain real parameter passes a certain validation rule(s). The logic part of the macro is composed of 2 parts:
param
is a real parameter, with a valid name. This is done by using the static_cast
, and if an illegal name is used, a compile time error will be generated.assertion
. This is done with a simple negating if statement.If the param is a valid name, and the assertion fails (assertion == false
), an InvalidParamError
is thrown, using the passed in parameters as strings (using the Stringizing operator #) to initialize the error object.
Since the actual usage of the param
parameter in the macro is only as a string, it has to be validated using actual code. Since no real operation is needed the static_cast is used, which discards the result and can potentially be optimized out. Without that check, you could pass any value which would make the information in the assertion meaningless.
Upvotes: 5
Reputation: 30489
static_cast<void>(param);
will evaluate the param
and discard the result.
If you don't add the cast to void
:
From cppreference
4) If new_type is the type void (possibly cv-qualified), static_cast discards the value of expression after evaluating it.
Upvotes: 1
Reputation: 2522
it is the 'c++ way' of writing
(void)param;
it makes 'use' of the variable and thus disables the compiler warning for unused variable
Upvotes: 2