bool passed by ref, safe or not ?

Paul Backus snarwin at gmail.com
Wed Jun 5 01:18:06 UTC 2024


On Tuesday, 4 June 2024 at 16:58:50 UTC, Basile B. wrote:
> ```d
> void main(string[] args)
> {
>     ushort a = 0b1111111111111111;
>     bool* b = cast(bool*)&a;
>     setIt(*b);
>     assert(a == 0b1111111100000000); // what actually happens
>     assert(a == 0b1111111111111110); // what would be safe
> }
> ```
>
[...]
>
> Do I corrupt memory here or not ?
> Is that a safety violation ?

`cast(bool*)&a` is a safety violation.

The only [safe values][1] for a `bool` are 0 (false) and 1 
(true). By creating a `bool*` that points to a different value, 
you have violated the language's safety invariants. Because of 
this, operations that would normally be safe (reading or writing 
through the `bool*`) may now result in undefined behavior.

[1]: https://dlang.org/spec/function.html#safe-values


More information about the Digitalmars-d-learn mailing list