CKTIS / C++
std::error_code: an error value paired with a category
std::error_code stores an integer value and a category that gives the value meaning and produces its message.
Version: C++23
Syntax
class error_code {
public:
error_code() noexcept;
error_code(int value, const std::error_category& category) noexcept;
int value() const noexcept;
const std::error_category& category() const noexcept;
std::string message() const;
explicit operator bool() const noexcept;
void clear() noexcept;
};std::error_code from <system_error> represents operating-system or low-level API failures without requiring an exception. The (value, category) constructor preserves both components, and message() delegates to category().message(value()).
Default construction and clear() set value 0 with std::system_category(). Explicit conversion to bool checks only value() != 0. std::make_error_code(std::errc) creates a code in generic_category(), so an integer without its category does not portably identify an error.
Comparing two error_code objects considers both value and category identity, while comparison with an error_condition can use category equivalence rules. Text from message() is implementation- and locale-dependent and can allocate; do not use it for program logic or stable tests.
Examples
#include <iostream>
#include <system_error>
int main() {
std::error_code error = std::make_error_code(std::errc::permission_denied);
std::cout << static_cast<bool>(error) << ' '
<< (error.category() == std::generic_category()) << ' ';
error.clear();
std::cout << static_cast<bool>(error) << '\n';
}
Result
1 1 0
std::error_code → 1 1 0