Radoslaw Krasimirow
Radoslaw Krasimirow

Reputation: 1873

When do we do typecast in #define

When do we use a typecasting in definitions like this:

#define MAGIC_NUMBER  (unsigned char)0x5D

And why is it necessary?

Upvotes: 4

Views: 7527

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

To answer

why is it necessary

without the explicit cast, 0x5D is considered as integer literal or integer constant, in hexadecimal form. With the cast, we try to explicitly make the representation of it as an unsigned char.

When do we use

is too broad and probably out of scope for an answer. One possible scenario, for example, is while supplying the MACRO as the argument to a %hhx format specifier, in case of printf() family.

Upvotes: 6

Related Questions