Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
improve wrap around example
Browse files Browse the repository at this point in the history
Akuli committed Dec 7, 2023
1 parent fe9f5be commit de30eeb
Showing 1 changed file with 16 additions and 14 deletions.
30 changes: 16 additions & 14 deletions doc/perf.md
Original file line number Diff line number Diff line change
@@ -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.

0 comments on commit de30eeb

Please sign in to comment.