V2507. MISRA. The body of a loop\conditional statement should be enclosed in braces.


This diagnostic rule is based on the software development guidelines developed by MISRA (Motor Industry Software Reliability Association).

The bodies of the statements 'while', 'do-while', 'for', 'if', 'if-else', and 'switch' should be enclosed in braces.

Braces clearly define which of the statements belong to the body, make the code clearer, and help to prevent certain errors. For example, with braces absent, the programmer could misinterpret indentation or overlook the ';' character written accidentally after the statement.

Example 1:

void example_1(....)
{
  if (condition)
    if (otherCondition)
      DoSmt();
  else
    DoSmt2();
}

The format of this code does not match its execution logic and may confuse the programmer. Adding the braces makes the code unambiguous:

void example_1(....)
{
  if (condition)
  {
    if (otherCondition)
    {
      DoSmt();
    }
    else
    {
      DoSmt2();
    }
  }
}

Example 2:

void example_2(....)
{
  while (count < 10)
    DoSmt1(); DoSmt2();
}

The format of this code does not match its execution logic either since only the 'DoSmt1()' expression belongs to the loop.

Fixed version:

void example_2(....)
{
  while (count < 10)
  {
    DoSmt1();
    DoSmt2();
  }
}

Note: an 'if' statement immediately following an 'else' statement does not have to be enclosed in braces. For example, the analyzer will keep silent about this code:

if (condition1)
{ .... }
else if (condition2)
{ .... }

Bugs Found

Checked Projects
344
Collected Errors
12 970