bool passed by ref, safe or not ?

Dukc ajieskola at gmail.com
Wed Jun 5 07:32:21 UTC 2024


Basile B. kirjoitti 4.6.2024 klo 19.58:
> I understand that the notion of `bool` doesn't exist on X86, hence what 
> will be used is rather an instruction that write on the lower 8 bits, 
> but with a 7 bits corruption.
> 
> Do I corrupt memory here or not ?
> Is that a safety violation ?
Viewing a valid boolean as an integer is still valid. Bit pattern of 
`false` is 0b0000_0000, and bit pattern of `true` is `0b0000_0001`. And 
even if the boolean is invalid, viewing it as an integer is probably 
valid if it was assigned to as an integer and not as an invalid boolean.

There's a related case though where the situation is unclear. How do 
`ubytes` other than 1 or 0, when viewed as bools? We probably can't say 
it's undefined behaviour, since it is allowed in `@safe`.

How I would define it, is that it's unspecific behaviour. That is if you 
have

```D
bool* unspecified = cast(bool*) new ubyte(0xff);
```

then

```
// same as void-initialising
bool a = *unspecified;
// also same as void-initialising
ubyte b = *unspecified;
// Reliably 0xff. It's using the memory slot as bool that makes it 
unspecified, but what's in the memory slot is not affected.
ubyte c = * cast(ubyte*) unspecified;

// Unspecified which happens. One and only one must happen though.
if (*unspecified) fun() else gun();

// Should this be required to call the same function as above? I'm not sure.
if (*unspecified) fun() else gun();
```




More information about the Digitalmars-d-learn mailing list