this is my first question 🙂
I have one pile file, and I have open it like shown below ;
ifstream in ( filename, ios :: binary | ios :: in )
Then, I wish hold 2 byte data in unsigned int hold ;
unsigned int hold;
in . read(static_cast<char *>(&hold), 2);
It seems correct to me. However, when I compile it with
g++ -ansi -pedantic-errors -Werror - -Wall -o main main.cpp
Compiler emits error
error: invalid static_cast from type ‘unsigned int*’ to type ‘char*’
Actually, I have solved this problem by changing static_cast with ( char*), that is
unsigned int hold;
in . read((char*)(&hold), 2);
My questions are :
- What is the difference(s) between
static_cast<char*>and(char*)? - I am not sure whether using
(char*)is a safer or not. If you have enough knowledge, can you inform me about that topic ?
NOTE : If you have better idea, please help me so that I can improve my question?
static_castis a safer cast than the implicit C style cast. If you try to cast an entity which is not compatible to another, thenstatic_castgives you an compilation time error unlike the implicit c-style cast.static_castgives you an error here because what you are trying to say is take anintand try to fit it in achar, which is not possible.intneeds more memory than whatcharoccupies and the conversion cannot be done in a safe manner.If you still want to acheive this,You can use
reinterpret_cast, It allows you to typecast two completely different data types, but it is not safe.The only guarantee you get with
reinterpret_castis that if you cast the result back to the original type, you will get the same value, But no other safety guarantees.