C++ Logo

std-proposals

Advanced search

Re: [std-proposals] A draft for modern switch

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Tue, 20 May 2025 09:52:07 -0400
On Tue, May 20, 2025 at 9:01 AM Zhao YunShan via Std-Proposals
<std-proposals_at_[hidden]> wrote:
> What are the advantages of match over switch in this paper?

For one, it's already a thing that's being worked on for
standardization. That's a pretty big advantage.

`switch` should not be looked on as something that has a future.


> Any optimizations specific to switch constructs?
>
>
> With the paper ID, I could try writing a paper about this.
>
>
> At 2025-05-20 19:48:03, "Jens Maurer" <jens.maurer_at_[hidden]> wrote:
> >
> >This says "draft". Is there a paper anywhere?
> >
> >Have you reviewed the pending pattern matching proposal(s),
> >such as https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p2688r5.html ?
> >
> >Thanks,
> >Jens
> >
> >
> >On 20/05/2025 13.38, Zhao YunShan via Std-Proposals wrote:
> >>
> >> In C++, the |switch| statement is a fundamental control-flow construct originally designed to work only with integer types (|int|, |char|, |enum|, etc.). However, in real-world development, programmers often need to handle string-based (|std::string|) branching logic. While the standard syntax does not natively support strings, well-structured design patterns can still leverage |switch|-like behavior to replace lengthy |if...else if| chains, significantly improving code readability and conciseness.
> >>
> >> #include<iostream>
> >> #include<string>
> >> int main()
> >> {
> >> std::string router;
> >> switch (router)
> >> {
> >> case "cpp":
> >> std::cout << "cpp router selected.";
> >> break;
> >> case "hpp":
> >> std::cout << "hpp router selected.";
> >> break;
> >> default:
> >> std::cout << "Unknown router type.";
> >> break;
> >> }
> >> return 0;
> >> }
> >>
> >>
> >> By leveraging compile-time static analysis, |switch| statements can be optimized into various efficient data structures:
> >> *
> >> *
> >> * Jump tables* for few cases,
> >> * Balanced binary search* for many branches,
> >> * Hash tables* where supported.
> >>
> >> This ensures optimal time complexity (*O(1)* to *O(log n)*) even with large branch sets.
> >>
> >>
>
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2025-05-20 13:52:24