Sujet : Re: how cast works?
De : 643-408-1753 (at) *nospam* kylheku.com (Kaz Kylheku)
Groupes : comp.lang.cDate : 09. Aug 2024, 22:30:33
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <20240809142622.467@kylheku.com>
References : 1 2 3 4 5 6 7 8 9
User-Agent : slrn/pre1.0.4-9 (Linux)
On 2024-08-09, James Kuyper <
jameskuyper@alumni.caltech.edu> wrote:
On 09/08/2024 12:04, Bart wrote:
On 09/08/2024 00:17, Keith Thompson wrote:
...
There is no such thing as an "implicit cast" in C.
>
Suppose I write this code:
x = a; // implicit 'conversion'
x = (double)a; // explicit 'conversion'
My compiler produces these two bits of AST for the RHS of both expressions:
1 00009 r64---|---2 convert: sfloat_c i32 => r64
1 00009 i32---|---|---1 name: t.main.a.1
1 00010 r64---|---2 convert: sfloat_c i32 => r64
1 00010 i32---|---|---1 name: t.main.a.1
>
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 *).
In computer science, we refer to unsafe conversion as coercion.
THe cast notation is C's coercion operation.
In some languages, some of what C allows to be an implicit conversion
would be classified as requiring a coercion.
It almost makes sense to speak of "implicit cast" (i.e. coercion) in C,
because of what happens implicitly being so unsafe.
-- TXR Programming Language: http://nongnu.org/txrCygnal: Cygwin Native Application Library: http://kylheku.com/cygnalMastodon: @Kazinator@mstdn.ca