m.divya.mohan
m.divya.mohan

Reputation: 2330

what is the use of "static_cast<void>" in macro?

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

Answers (3)

Amit
Amit

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:

  1. Validate that 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.
  2. Validate the "truthyness" of 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

Mohit Jain
Mohit Jain

Reputation: 30489

static_cast<void>(param); will evaluate the param and discard the result.

If you don't add the cast to void:

  1. you may get warnings saying you are ignoring the result of expression.
  2. Even if you pass some illegal code (for example a statement instead of expression) as argument, compiler will accept it happily.

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

Zaiborg
Zaiborg

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

Related Questions