unsafe bug ?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

Using VS2005 I'm trying out some unsave code but have some strange results.
My english is not well so I give example:

private void testToolStripMenuItem2_Click(object sender, EventArgs e)
{
char[] ttt = "5".ToCharArray();
test(ttt);
}

unsafe void test(char[] _a)
{
fixed (char* a = _a) {
double t = *a - 0x30;
t /= 10;
double tt = (*a - 0x30) / 10;
}
}

In the procedure test, t is 0.5 in second line witch is correct. But tt is
0. Wy ? It is exacly same code unless I'm missing somting...
 
Wilfried Mestdagh said:
Using VS2005 I'm trying out some unsave code but have some strange results.
My english is not well so I give example:

private void testToolStripMenuItem2_Click(object sender, EventArgs e)
{
char[] ttt = "5".ToCharArray();
test(ttt);
}

unsafe void test(char[] _a)
{
fixed (char* a = _a) {
double t = *a - 0x30;
t /= 10;
double tt = (*a - 0x30) / 10;
}
}

In the procedure test, t is 0.5 in second line witch is correct. But tt is
0. Wy ? It is exacly same code unless I'm missing somting...

No, it's not the same code. The expression t /= 10 is performing a
division of a double by an integer - so the integer is promoted to a
double and the calculation is performed in floating point.

Compare this with (*a-0x30) / 10, which is performing a division of a
char by an integer, so the char is promoted to an int and the
calculation is performed in integer arithmetic.
 

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

Back
Top