What is the difference between static_cast<> and C style casting?

C++Server Side ProgrammingProgramming

Here we will see what are the differences between static_cast<> and normal C style cast.

The normal cast like (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

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.

raja
Published on 02-May-2019 16:06:59
Advertisements