Re: Simple Casting Question
- From: alex.j.k2@xxxxxxxxx
- Date: Mon, 19 May 2008 08:09:23 -0700 (PDT)
On May 19, 10:06 am, Nick Keighley <nick_keighley_nos...@xxxxxxxxxxx>
wrote:
I have a function that does large amounts of computations
(divisions, square roots, etc.) for large datasets.
not so good...
#include <math.h>
#include <stdio.h>
int main (void)
{
double d1 = 5, d2;
int i1 = 5, i2;
d2 = sqrt(d1);
i2 = sqrt(i1);
printf ("square root 5 is %f\n", d2);
printf ("square root 5 is %d\n", i2);
return 0;
}
I submit if you did a series of computations
using d2 then i2 you'd get wildly diverging results.
There is not a single place in my code where the
returned value of sqrt() can be attributed to an integer.
For efficiency reasons
more sins have been committed in the name of efficiency...
Do you mean faster? How do you know the floating point
version is too slow? Have you measured it?
It's mainly about the size of the input data. Some of
my datasets are large enough that storing it as float or int
is significantly more efficient that storing it as double.
I do make sure in the preprocessor code that all casting is done
only in the form (int to float), (float to double), (int to double),
I don't see how this helps. If you don't know the type how can you
ensure this?
It helps for instance by avoiding the need for casting
and thus relying on implicit conversions. As another example,
all the types that may store square roots, are forced to be
either float or double.
I do know the type in the preprocessor code. I just want
to allow the ability to change the type in said preprocessor
code.
I am curios about the subtle and not so subtle bugs introduced
by overenthusiastic uses of casting.
Do you have a reference/link/short paragraph related to this theme?
there's the malloc example.
I once saw this code:
void f (char str)
{
strcpy (str, "bing");
}
It failed to compile. So the programmer fixed it thus:-
void f (char str)
{
strcpy ((char*)str, "bing");
}
That's funny. Thanks for the examples.
To summerise:
1. I think your PRECISION macro is a bad idea
Well, some think coding in C is a bad idea. I think
the macro is useful for my purposes.
2. avoid casting as much as possible
That I will do.
Alex
.
- References:
- Simple Casting Question
- From: alex . j . k2
- Re: Simple Casting Question
- From: Keith Thompson
- Re: Simple Casting Question
- From: alex . j . k2
- Re: Simple Casting Question
- From: Nick Keighley
- Simple Casting Question
- Prev by Date: Re: Determine the size of malloc
- Next by Date: Re: Determine the size of malloc
- Previous by thread: Re: Simple Casting Question
- Next by thread: Re: Simple Casting Question
- Index(es):
Relevant Pages
|