M
mike3
Hi.
I heard that in C++ typecasts are "evil". However, what does one do
with this thing?:
---
/* Figure out how many digits of fraction we'll get.
* We add 1 to the lengths of a and b to take into account
* the hidden bits.
*/
int fracObtained(((aLength + 1) - (bLength + 1)));
std::size_t bufExtra(0);
if((fracObtained < rLength) || (fracObtained < MIN_PRECISION))
<---- yuck
{
/* We need more */
bufExtra = rLength - fracObtained;
}
---
But if I simply do
---
/* Figure out how many digits of fraction we'll get.
* We add 1 to the lengths of a and b to take into account
* the hidden bits.
*/
int fracObtained(((aLength + 1) - (bLength + 1)));
std::size_t bufExtra(0);
if(fracObtained < rLength) <--- nice but doesn't work due to
signed/unsigned comparison
{
/* We need more */
bufExtra = rLength - fracObtained;
}
---
it fails when "fracObtained" is negative, because rLength is also of
type std::size_t, which
is an unsigned type. The former code uses no typecast, the latter
doesn't either, but the
former works however it having that goofy extra check in there may be
confusing while
the latter, simply comparing it to rLength seems clearer and more
natural. But for the latter to work,
you need a typecast of rLength to int. But is the "evil" here
necessary if one wants to
write good code for this?
I heard that in C++ typecasts are "evil". However, what does one do
with this thing?:
---
/* Figure out how many digits of fraction we'll get.
* We add 1 to the lengths of a and b to take into account
* the hidden bits.
*/
int fracObtained(((aLength + 1) - (bLength + 1)));
std::size_t bufExtra(0);
if((fracObtained < rLength) || (fracObtained < MIN_PRECISION))
<---- yuck
{
/* We need more */
bufExtra = rLength - fracObtained;
}
---
But if I simply do
---
/* Figure out how many digits of fraction we'll get.
* We add 1 to the lengths of a and b to take into account
* the hidden bits.
*/
int fracObtained(((aLength + 1) - (bLength + 1)));
std::size_t bufExtra(0);
if(fracObtained < rLength) <--- nice but doesn't work due to
signed/unsigned comparison
{
/* We need more */
bufExtra = rLength - fracObtained;
}
---
it fails when "fracObtained" is negative, because rLength is also of
type std::size_t, which
is an unsigned type. The former code uses no typecast, the latter
doesn't either, but the
former works however it having that goofy extra check in there may be
confusing while
the latter, simply comparing it to rLength seems clearer and more
natural. But for the latter to work,
you need a typecast of rLength to int. But is the "evil" here
necessary if one wants to
write good code for this?