I've read that reinterpret_cast<>
can be dangerous if not used properly. So I believe that i was using it properly ;). I found it's good to use if I've templates classes and type conversion is required on that. But recently I've read that reinterpret_cast<>
is non-portable too. I'm sad for this point. What's the reason? Take the following code,
void Disp(int* val)
{
for (int i=0; i < SZ; ++i)
{
cout << *(val+i) << " ";
}
cout << endl;
}
int main()
{
int arr[SZ];
Disp(arr);
unsigned char* ptr = reinterpret_cast<unsigned char*>(arr);
for (unsigned char* i = ptr; i < (ptr + (SZ * sizeof(int))); i++)
{
*i = 0;
}
Disp(arr);
return 0;
}
Now the outputs:
1174214872 32767 4196789 0 568392584 58 4196720 0 0 0
0 0 0 0 0 0 0 0 0 0
Machine type: Linux 2.6.32-358.11.1.el6.x86_64 #1 x86_64 x86_64 x86_64 GNU/Linux
975580 -16506540 -13369152 0 -4202936 67876 3 -4202836 4 -4202828
0 0 0 0 0 0 0 0 0 0
Machine type: SunOS DELPHI 5.10 Generic_142900-01 sun4u sparc SUNW,Netra-240
I've copied the outputs of the same program, both in Linux and Solaris. I'm new to portability issues. So can anyone please tell me, if I'm using something like this in my code, will that cause any portability issues? Even if not with this code, is there a chance for surprises (undefined behavior) when the code get complex (with dynamic allocation and all) and running for long hours. Thanks for the help.