- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why use static_cast<int>(x) instead of (int)x in C++?
45 Lectures 4.5 hours
66 Lectures 5.5 hours
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.
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.
- MySQL - CAST DECIMAL to INT?
- How to plot int to datetime on X-axis using Seaborn?
- How to cast from VARCHAR to INT in MySQL?
- What does the method fill(int, int fromIndex, int toIndex, int val) do in java?
- int(5) vs. int(10) in MySQL?
- Difference between const int*, const int * const, and int const * in C
- Difference between const int*, const int * const, and int const * in C/C++?
- What does the method sort(int a, int fromIndex, int toIndex) do in java?
- What does the method copyOfRange(int original, int from, int to) do in java?
- What is the difference between const int*, const int * const, and int const *?
- What does the method fill(obj, int fromIndex, int toIndex, int val) do in java?
- Why do we use WebDriver instead of Selenium IDE?
- Python - int() function
- What does the method fill(int, int val) do in java?
- Matcher region(int start, int end) method in Java with Examples