From de30eeb842b1de3fd50ee2bb585260ea1908e095 Mon Sep 17 00:00:00 2001 From: Akuli Date: Thu, 7 Dec 2023 18:32:08 +0200 Subject: [PATCH] improve wrap around example --- doc/perf.md | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/doc/perf.md b/doc/perf.md index 4c2d52cd..6b3e2144 100644 --- a/doc/perf.md +++ b/doc/perf.md @@ -279,23 +279,25 @@ The takeaway from this is that these are all things that one would never do inte The rest of Jou's documentation aims to mention other things that are UB. In some other languages, it is easier to get UB than in Jou. -For example, in C it is UB to add two signed `int`s so large +For example, in C it is UB to add two `int`s so large that the result doesn't fit into an `int`, -but in Jou, math operations are guaranteed to "wrap around". -For example, Jou's `byte` is an unsigned 8-bit number, -so it has a range from 0 to 255, and bigger values wrap back around to 0: +but in Jou, math operations are instead guaranteed to wrap around: ```python -printf("%d\n", (255 as byte) + (1 as byte)) # Output: 0 -``` +import "stdlib/io.jou" -Here's what this looks like with `int`: +def main() -> int: + printf("%d\n", (254 as byte) + (0 as byte)) # Output: 254 + printf("%d\n", (254 as byte) + (1 as byte)) # Output: 255 + printf("%d\n", (254 as byte) + (2 as byte)) # Output: 0 + printf("%d\n", (254 as byte) + (3 as byte)) # Output: 1 + printf("%d\n", (254 as byte) + (4 as byte)) # Output: 2 + + printf("%d\n", 2147483646 + 0) # Output: 2147483646 + printf("%d\n", 2147483646 + 1) # Output: 2147483647 + printf("%d\n", 2147483646 + 2) # Output: -2147483648 + printf("%d\n", 2147483646 + 3) # Output: -2147483647 + printf("%d\n", 2147483646 + 4) # Output: -2147483646 -```python -printf("%d\n", 2147483647 + 1) # Output: -2147483648 + return 0 ``` - -The numbers are bigger, because `int` in Jou is 32 bits and `byte` is only 8 bits. -This time, the "wrapped around" result is negative, because `int` is signed. -In C this would be UB with a signed type (such as `int`), -but in Jou, overflowing integers is never UB.