- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the difference between static_cast<> and C style casting?
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.
- Related Articles
- What is the difference between up-casting and down-casting in Java?
- What is the difference between type conversion and type casting in C#?
- Difference between Casting and Forging
- What is the difference between old style and new style classes in Python?
- Difference Between Type casting and Type Conversion
- What are the differences between Widening Casting (Implicit) and Narrowing Casting (Explicit) in Java?
- What is the difference Between C and C++?
- What is Type casting in C#?
- What is Casting operators in C++?
- Dynamic_cast and static_cast in C++
- What is the difference between JavaScript and C++?
- What is the difference between C++0x and C++11?
- What is the difference between | and || operators in c#?
- static_cast in C++
- What are up-casting and down-casting in Java?
