More readable way of casting primitive types in C++

How to cast a variable of one primitive type to another? Usually people use static_cast operator, but it can be done in other, more readable way.

Below example demonstrate the problem, and two solutions:

char var1 = 3;
char var2 = 5;

// first way
int result1 = static_cast<int>(var1 + var2);

// second way
int result2 = int(var1 + var2);

The same trick may be used e.g. when passing to a function an argument of different type that expected.

There is also C-style casting available in C++, but I didn't mention it above because it's discouraged.

Yes, I know, casting from one type to another is a common source of bugs, and can signify that overall design could be improved. That's true, but sometimes it's inevitable.

0 commentaires:

Post a Comment