C++ Logo

std-proposals

Advanced search

[std-proposals] A draft for modern switch

From: Zhao YunShan <dou1984_at_[hidden]>
Date: Tue, 20 May 2025 19:38:24 +0800 (CST)
    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>
intmain()
{
    std::stringrouter;
    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;
    }
    return0;
}




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.

Received on 2025-05-20 11:38:30