This diagnostic rule is based on the software development guidelines developed by MISRA (Motor Industry Software Reliability Association).
Variables should be declared in as narrow a scope as possible. This will help to avoid potential errors caused by inadvertent use of variables outside their intended scope, as well as minimize memory consumption and increase the program's performance.
Example of non-compliant code:
static void RenderThrobber(RECT *rcItem, int *throbbing, ....)
{
....
int width = rcItem->right - rcItem->left;
....
if (*throbbing)
{
RECT rc;
rc.right = width;
....
}
.... // width is not used anywhere else
}
The 'width' variable is used only inside the 'if' block; therefore, it would be reasonable to declare it inside that block. That way, 'width' will be evaluated only if the condition is true, thus saving time. In addition, this will help to prevent incorrect use of the variable in the future.
This diagnostic is classified as:
|