Sujet : Re: how cast works?
De : jameskuyper (at) *nospam* alumni.caltech.edu (James Kuyper)
Groupes : comp.lang.cDate : 09. Aug 2024, 23:35:52
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v965k8$788h$3@dont-email.me>
References : 1 2 3 4 5 6 7 8 9 10
User-Agent : Mozilla Thunderbird
On 8/9/24 17:30, Kaz Kylheku wrote:
On 2024-08-09, James Kuyper <jameskuyper@alumni.caltech.edu> wrote:
...
Of course - an implicit conversion has exactly the same effect as a
explicit conversion, if the source and destination types are the same.
That doesn't make it correct to use the term "cast" to describe anything
other than an explicit conversion.
>
That's all very neat and clean. However, the problem is that in C,
some of the implicit conversions are unsafe.
>
Implicit conversions can:
>
- truncate an integer value to fit a narrower type.
>
- convert between floating point and integer in a way that the value
is out of range, with undefined behavior ensuing.
>
- change the value: e.g -1 becomes UINT_MAX.
>
- subvert the type system, e.g. (foo *) -> (void *) -> (bar *).
The implicit conversions are implicit precisely because they tend to be
safer than the ones that cannot be done implicitly. That doesn't mean
that they're safe.
In computer science, we refer to unsafe conversion as coercion.
THe cast notation is C's coercion operation.
Yes, and in the C standard, conversions are simply called conversions,
regardless of how unsafe they are - for instance, you can't get much
less safe than (void (*))printf; but it's still a conversion. It's
confusing to discuss C using terms that have a standard-defined meaning,
if you insist on using them with a conflicting meaning.
It almost makes sense to speak of "implicit cast" (i.e. coercion) in C,
because of what happens implicitly being so unsafe.
No, it doesn't. If lack of safety is what makes them implicit, then
casts should be even more implicit than implicit conversions.