Skip to content

Commit f26e1c5

Browse files
authored
[spec] Document unsafe bool operations (#3844)
[spec] Document unsafe bool operations Signed-off-by: Dennis <dkorpel@users.noreply.github.com> Signed-off-by: Nicholas Wilson <thewilsonator@users.noreply.github.com> Merged-on-behalf-of: Nicholas Wilson <thewilsonator@users.noreply.github.com>
1 parent 59d51b2 commit f26e1c5

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

spec/expression.dd

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1358,6 +1358,9 @@ $(H4 $(LNAME2 cast_array, Arrays))
13581358
---
13591359
)
13601360

1361+
$(UNDEFINED_BEHAVIOR Casting a non-literal array to `bool[]` when any
1362+
element has a byte representation $(DDSUBLINK spec/type, bool, other than 0 or 1).)
1363+
13611364
$(DDOC_SEE_ALSO $(RELATIVE_LINK2 cast_array_literal, Casting array literals).)
13621365

13631366
$(H4 $(LNAME2 cast_static_array, Static Arrays))

spec/type.dd

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -573,9 +573,25 @@ $(P A `bool` value can be implicitly converted to any integral type, with
573573

574574
$(P The numeric literals `0` and `1` can be implicitly converted to the `bool`
575575
values `false` and `true`, respectively. Casting an expression to `bool` means
576-
testing for `0` or `!=0` for arithmetic types, and `null` or `!=null` for
576+
testing `!=0` for arithmetic types, and `!=null` for
577577
pointers or references.)
578578

579+
$(UNDEFINED_BEHAVIOR)
580+
* Interpreting a value with a byte representation
581+
other than 0 or 1 as `bool` (e.g. an overlapped union field).
582+
* Reading a `void`-initialized `bool`.
583+
584+
$(SPEC_RUNNABLE_EXAMPLE_RUN
585+
---
586+
byte i = 2;
587+
bool b = cast(bool) i; // OK, same as `i != 0`
588+
assert(b);
589+
590+
bool* p = cast(bool*) &i; // unsafe cast
591+
// `*p` holds 0x2, an invalid bool value
592+
// reading `*p` is undefined behavior
593+
---
594+
)
579595

580596
$(H2 $(LNAME2 functions, Function Types))
581597

0 commit comments

Comments
 (0)