Type casting

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????

I am new to c++ ...please help


thanks
Venkata
Typecasting is less common, but a good example is rounding:
1
2
3
double x = 5.678;
int y1 = int(x); //typecast; round down to 5
int y2 = int(x+0.5); //typecast; round to nearest (6) 
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.
Last edited on
Rounding:
std::round() and friends http://en.cppreference.com/w/cpp/numeric/math/round
std::rint() and friends http://en.cppreference.com/w/cpp/numeric/math/rint
and std::nearbyint() http://en.cppreference.com/w/cpp/numeric/math/nearbyint


1
2
3
4
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.
Last edited on
Topic archived. No new replies allowed.