What does reinterpret_cast<char *>(&st) and (-1)*static_cast<int> mean?

11.3k views Asked by At

The code here is being used for creating a Student Report card project. While trying to understand we can not figure out the use of and functions of the below code:

File.read(reinterpret_cast<char *> (&st), sizeof(student));

int pos=(-1)*static_cast<int>(sizeof(st));

File.read(reinterpret_cast<char *> (&st), sizeof(student));
if(st.retrollno()==n)
    {
    st.showdata();
    cout<<"\n\nPlease Enter The New Details of student"<<endl;
        st.getdata();
            int pos=(-1)*static_cast<int>(sizeof(st));
            File.seekp(pos,ios::cur);
            File.write(reinterpret_cast<char *> (&st), sizeof(student));
            cout<<"\n\n\t Record Updated";
            found=true;
    }
3

There are 3 answers

1
StoryTeller - Unslander Monica On

File.read(reinterpret_cast<char *> (&st), sizeof(student)); Reads the student structure data directly from a file into the memory occupied by st.

The cast is because read expects a char*, and this is how you convert a pointer of one type to a pointer of a completely unrelated type.

Such code will only work when the file is written to and read from in binary mode, not to mention you pretty much have to create the file and read it on the exact same machine to be certain it will work as expected.

Even then, if the structure contains pointers, it's likely doomed to fail.


(-1)*static_cast<int>(sizeof(st)); turns the unsigned result of the sizeof operator into a signed number, and multiplies it by -1.


The lines above feature what is called -style casts. The reason for using those, is that unlike a -style cast, they will not preform a cast at any cost. They will only cast if the conditions for casting are met, which is much safer.

So casting unsigned to signed only requires a static_cast, which will fail if the compilers static type checking doesn't hold.

reinterpret_cast is a much more powerful beast (which is required when you want to somewhat ignore the type system), but still has some safeguards compared to a c-style cast.

0
Charbel On

It is multiplying it by - 1 to go back 1 location. since the sizeof function in c++ returns an unsigned integer so the static_cast will convert the unsigned to signed and then multiply it by - 1 so the position is negative so the pointer will go to the desired location and stay there which will allow you to modify data.

1
yash On

click here to see the image you can use the method that i had used if you are not able to understand what is File.read(reinterpret_cast<char *> (&st), sizeof(student)); and, int pos=(-1)*static_cast<int>(sizeof(st)); doing and want to understand the code right now....