Slides for P3793R0 — Better shifting
- Document number:
- P3898R0
- Date:
2025-11-02 - Audience:
- SG6
- Project:
- ISO/IEC 14882 Programming Languages — C++, ISO/IEC JTC1/SC22/WG21
- Reply-to:
- Jan Schultke <janschultke@gmail.com>
- Source:
- github.com/Eisenwave/cpp-proposals/blob/master/src/better-shifting-slides.cow
- →, ↓ : go to the next slide
- ←, ↑ : go to previous slide
Better shifting
P3793R0
Introduction
- bit-shifting (
and<< ) is not ideal:>> - hard-to-remember precedence rules
- undefined behavior on "overlong" shifts
- other languages, hardware use modular shift amount (C#, Java, JS)
- "fixing" bit-shifts in core language difficult
- at best, unspecified result + erroneous behavior
- proposed: "mathematically correct"
andstd :: shl std :: shr
Motivation
"Mathematically correct" functions eliminate special cases and UB pitfalls:
| Before | After |
|---|---|
|
|
|
|
|
|
Design choices
orstd :: shl N-bit shift acts like N single-bit shiftsstd :: shr - no wrapping behavior because it's not useful
- no separate logical/arithmetic right-shift (change signedness to choose)
- negative shifts have erroneous behavior with impl-defined result
- no added runtime cost on release builds, no UB 🎉
- function names inspired by
andstd :: rotl std :: rotr - shift amount passed as
(likeint andstd :: rotl )std :: rotr - SIMD support added, similar to
std :: simd :: rotl
Possible implementation
References
[P3724R1]
Integer division
2025-09-29
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p3724r1.html
[StackOverflowCeil]
Fast ceiling of an integer division in C / C++
https://stackoverflow.com/q/2745074/5740428