why do we generally do typecasting ....my question is if i write a code below
inta=6;
int ptr=&a;
int b= reinterpret_cast<int>(ptr);
and print b then it is printing something that is totally unrelated(neither the value of a nor the address of a)
then why do we genrally use typecasting????in what kind of scenarios ????when there are lots of chances that they invite lots of vague values into the program????
In C, casting is routine. For example, you cast when you obtain a memory block from an allocator.
In C++, this is not the case. Casting should be considered an exception event.
C and C++ and typed languages. C++ has a number of stricter type checks. But what make C/C++ practical is that these protections can be overridden. However, when you override a type check, you the programmer take full responsibility for the conversion and its consequences.
In your example, you need a cast because your doing something possibly pointless, but definitely unsafe. You're storing the address of a variable in an int variable. These are two different things and only you know why you would want to do that, so you must override the language type system to force that assignment thru.
inta=6;
int ptr=&a;
// int b= reinterpret_cast<int>(ptr); // an int may not be able to hold the value of a pointer
std::uintptr_t b = reinterpret_cast<std::uintptr_t>(ptr) ;
One reason why you might want to do something like this: you want to write a custom hash function for a hash table where the key is a pointer.