This is the simplest type casting operator available in C++. The “static_cast” operator performs a normal cast. This casting operator is basically a substitute for normal casting operator. “static_cast” operator doesn’t do any runtime checks. Hence programmer should consider whether casting is applicable or not.
Normal syntax to do static_cast is as follows:
static_cast <target-type> (expr)
target-type is the target of the cast whereas expr is being cast into the new target-type.
Important Points
- This is the simplest casting operator which is basically a substitute of normal casting.
- This operator doesn’t perform any run time checks.
- This cast operator simply performs a non-polymorphic cast.
- This cast operator throws compile time error if casting is not possible.
Let’s have a look at the sample program to understand static_cast operator functionality.
#include <iostream>
int main ()
{
int i = 70;
cout << "Initial value: " << i << " After casting as char: " << static_cast <char> (i) << endl;
}
Let’s analyze the output of above program.
Initial value: 70 After casting as char: F
Difference between normal cast and static_cast
Normal cast doesn’t check the viability of casting being applied on a variable. However, static_cast check the viability of cast being applied on a variable. Hence it throws compile time error in case type casting is incompatible.
Let’s have a look at the example to understand it better.
void fun ()
{
int i = 70;
char *x = (char *)&i; /* No compile error */
/* Below line will throw compile error */
cout << "Initial value: " << i << " After casting as char: " << static_cast <char *> (i) << endl;
}
If above code is compiled then it will throw following error.
casting_operator.cpp: In function ‘void fun()’:
casting_operator.cpp:86:89: error: invalid static_cast from type ‘int’ to type ‘char*’
6 | cout << "Initial value: " << i << " After casting as char: " << static_cast <char *> (i) << endl;