Why use static_cast<int>(x) instead of (int)x in C++?

C++Server Side ProgrammingProgramming

The (int)x is C style typecasting where static_cast<int>(x) is used in C++. This static_cast<>() gives compile time checking facility, but the C style casting does not support that. This static_cast<>() can be spotted anywhere inside a C++ code. And using this C++ cast the intensions are conveyed much better.

In C like cast sometimes we can cast some type pointer to point some other type data. Like one integer pointer can also point character type data, as they are quite similar, only difference is character has 1-byte, integer has 4-bytes. In C++ the static_cast<>() is more strict than C like casting. It only converts between compatible types.

Example Code

char c = 65; //1-byte data. ASCII of ‘A’
int *ptr = (int*)&c; //4-byte

Since in a 4-byte pointer, it is pointing to 1-byte of allocated memory, it may generate runtime error or will overwrite some adjacent memory.

In C++ the static_cast<>() will allow the compiler to check whether the pointer and the data are of same type or not. If not it will raise incorrect pointer assignment exception during compilation.

char c = 65; //1-byte data. ASCII of ‘A’
int *ptr = static_cast<int>(&c);

This will generate compile time error.

Published on 02-Apr-2019 12:09:14