explict conversion from double to int - regarding overflow handling

F

Felix

I am a bit confused as to why conversion from float/double to int is
handled in c# in the way that it is. It differs from my implementation
of C and C++ in a suprising way (to me).

Here is a code snippet to reproduce my suprise:

// c#
int max = int.MaxValue;
Console.Out.WriteLine("max = " + max);
Console.Out.WriteLine("(int)(max + 1.0) = " + (int)(max + 1.0));
Console.Out.WriteLine("(int)(max + 2.0) = " + (int)(max + 2.0));
Console.Out.WriteLine("(int)(max + 1) = " + (int)(max + 1));
Console.Out.WriteLine("(int)(max + 2) = " + (int)(max + 2));

output:
1. max = 2147483647
2. (int)(max + 1.0) = -2147483648
3. (int)(max + 2.0) = -2147483648
4. (int)(max + 1) = -2147483648
5. (int)(max + 2) = -2147483647

// c
int max = 2147483647;

printf("max = %d\n", max);
printf("(int)(max + 1.0) = %d\n", (int)(max + 1.0));
printf("(int)(max + 2.0) = %d\n", (int)(max + 2.0));
printf("(int)(max + 1) = %d\n", (int)(max + 1));
printf("(int)(max + 2) = %d\n", (int)(max + 2));

1. max = 2147483647
2. (int)(max + 1.0) = -2147483648
3. (int)(max + 2.0) = -2147483647
4. (int)(max + 1) = -2147483648
5. (int)(max + 2) = -2147483647

notice how line #3 yield different results!

So I read the c# language spec, and it appears that it is legal to do
what I am seeing, BUT I think it is counter to what most programmers
would expect. I also read the c++ language spec, and again the
behavior I expected is not guarenteed! Wow! Is this suprising to any
of you guys?

Felix
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top