This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 22.4.1 - The literal value zero shall be the only value assigned to errno
Category: Required
Analysis: Decidable,Single Translation Unit
Amplification
Note: the C++ Standard Library is permitted to assign a non-zero value to errno.
Rationale
Various functions within the C++ Standard Library set errno to a non-zero value to indicate that an error has been detected.
This rule allows this error reporting behaviour to be used, but prevents developers from using errno as an error reporting mechanism
within a project’s code. C++ provides better mechanisms for error handling.
Example
std::string getKey ( std::optional< std::string > const & key_data )
{
if ( key_data.has_value() && !key_data->empty() )
{
return key_data.value();
}
errno = 42; // Non-compliant - non-zero value
errno = EINVAL; // Non-compliant - does not expand to literal '0'
return std::string {};
}
#define OK 0
void f()
{
uint32_t success { 0 };
errno = success; // Non-compliant - must use literal '0'
errno = OK; // Compliant - 'OK' expands to literal '0'
errnoSettingFunction();
if ( errno != success )
{
handleError();
}
}
Copyright The MISRA Consortium Limited © 2023