Re: Casts
- From: Flash Gordon <spam@xxxxxxxxxxxxxxxxxx>
- Date: Sat, 23 Jun 2007 23:32:48 +0100
jacob navia wrote, On 23/06/07 22:53:
Keith Thompson wrote:
<snip>
It's not correct to say that a cast *is* a conversion (or
tranformation); rather, a cast *specifies* a conversion. Conversions
can occur without the use of a cast.
The operand of a cast is an expression, not necessarily an object.
All expressions return a result object...
Not in C they don't. In C an object is a "region of data storage...".
> and that object is converted.
Conversions can only act in objects whose values are converted
isn't it?
No, conversions only apply to values in C.
Or are we getting into philosophy??? :-)
No, the definition of the language.
I can accept not using the language of the C standard where it would confuse a novice, but not using language in direct contradiction of the C standard.
Briefly, though, the real problem with casts is that they often carry
an implicit message to the compiler of "I know what I'm doing, don't
bother me with warnings". Very often, this isn't the case, and the
result is errors that aren't diagnosed by the compiler.
You don't mention another case where casts are appropriate: coercing
an argument to a variadic function (such as printf) to the required
type. For non-variadic functions, if you have a prototype in scope,
this coercion will usually be done automatically. For variadic
functions, the compiler lacks enough information to determine the
proper type, so it's up to the programmer.
You are right.
I added:
Another case when casts are necessary occurs when passing arguments to a
How can it be "another case when casts are necessary" when the cases you listed casts were not necessary?
variadic function. Since the type of the arguments can’t be known by the compiler, it is necessary to cast a value to its exact expected type (double to float for example),
Very bad example as the float will immediately be promoted back up to a double before being passed to the variadic function.
> so that the arguments are converted to
the exact types the variadic function expects.
For instance
float f;
printf("%Lg\n",(long double)f);
The printf function expects a long double (format Lg). We need to
convert our float f into a long double to match the expectations of
printf.
That, however, is a case where it is needed but it is pointless since you could just use the correct format specifier for a double instead. Printing a pointer value would be a better example.
--
Flash Gordon
.
- Follow-Ups:
- Re: Casts
- From: jacob navia
- Re: Casts
- Prev by Date: Re: Casts
- Next by Date: Re: Casts
- Previous by thread: Re: Casts
- Next by thread: Re: Casts
- Index(es):
Relevant Pages
|