jacob navia said:
Keith Thompson wrote: [...]
The operand of a cast is an expression, not necessarily an object.
All expressions return a result object... and that object is converted.
Conversions can only act in objects whose values are converted
isn't it?
Or are we getting into philosophy???
No, we're getting into the actual meanings of words.
Expression do not return objects; they yield values. Objects are not
converted; values are converted. Objects have values, but values are
not objects. In the expression
(int)1.5
*there is no object*. (Conceivably the compiler might store a
temporary value somewhere, but that's not an "object" in the C sense;
for example, it has no address.)
An "object" is a "region of data storage in the execution environment,
the contents of which can represent values" (C99 3.14).
[...]
I added:
Another case when casts are necessary occurs when passing arguments to
a 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), 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's not a great example. It would make much more sense to use the
"%g" format, which expects a double -- and a float argument is
promoted to double anyway. Or if you really wanted a long double, you
could declare f as a long double, and again, no cast is necessary.
I think an example involving integer types would illustrate the point
better. For example:
printf("sizeof obj = %lu\n", (unsigned long)sizeof obj);
where sizeof obj is of type size_t. (C99 provides the "%zu" format,
which does expect a size_t, but it's not universally supported.)