Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::errc — portable error conditions

std::errc is a scoped enumeration from <system_error>. It distinguishes named error conditions, including invalid_argument and result_out_of_range. With std::from_chars, check both ec and ptr when the entire input must be consumed.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <system_error>

std::errc status{};
status = std::errc::invalid_argument;
status = std::errc::result_out_of_range;

std::errc is a scoped enumeration declared in <system_error>. Its named values describe portable error conditions. std::errc::invalid_argument corresponds to EINVAL, and std::errc::result_out_of_range corresponds to ERANGE. Compare names rather than hard-coding numeric values. Assigning one of these values does not itself throw an exception.

The precise meaning depends on the function. For std::from_chars from <charconv>, std::errc::invalid_argument means that no characters matched the numeric pattern. std::errc::result_out_of_range means that the recognized number is not representable in the destination type. In both cases, the destination variable remains unchanged.

A successful conversion sets ec to std::errc{}. This does not guarantee that the entire input was consumed: for "42x", the number is parsed and ptr points to x. Complete conversion requires both result.ec == std::errc{} and result.ptr == end. The example constructs an out-of-range input by appending 0 to the type's maximum value in decimal, without assuming a particular width for unsigned int.

Examples

#include <charconv>
#include <iostream>
#include <limits>
#include <string>
#include <system_error>

int main() {
    const std::string inputs[] = {
        "42",
        "abc",
        std::to_string(std::numeric_limits<unsigned int>::max()) + "0",
        "42x"
    };

    for (const auto& text : inputs) {
        unsigned int value = 7;
        const char* end = text.data() + text.size();
        const auto result = std::from_chars(text.data(), end, value);

        if (result.ec == std::errc::invalid_argument) {
            std::cout << "invalid_argument";
        } else if (result.ec == std::errc::result_out_of_range) {
            std::cout << "result_out_of_range";
        } else if (result.ec == std::errc{} && result.ptr == end) {
            std::cout << "complete";
        } else {
            std::cout << "partial";
        }
        std::cout << " value=" << value << '\n';
    }
}

Result

complete value=42
invalid_argument value=7
result_out_of_range value=7
partial value=42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources