6.4 Declaration statement

6.4.1 Postpone variable definitions as long as possible

To preserve locality of reference, variables with automatic storage duration should be defined just before they are needed, preferably with an initializer, and in the smallest block containing all the uses of the variable.

#include <cstdint>
               
int32_t f1 (int32_t v)
{
int32_t i;         // @@- Non-Compliant -@@
                 
if ((v > 0) && (v < 10))
{
i = v * v;
--i;
return i;
}
return 0;
}
               
int32_t f2 (int32_t v)
{
if ((v > 0) && (v < 10))
{
int32_t i (v*v); // @@+ Compliant +@@
--i;
return i;
}
return 0;
}

The scope of a variable declared in a for loop initialization statement extends only to the complete for statement. Therefore, potential use of a control variable outside of the loop is naturally avoided.

#include <cstdint>
               
int32_t f3 (int32_t max)
{
int32_t i;
for (i = 0; i < max; ++i)         // @@- Non-Compliant -@@
{
}
return i;
}
               
void f4 (int32_t max)
{
for (int32_t i (0); i < max; ++i) // @@+ Compliant +@@
{
}
}

References

  • HIC++ v3.3 - 5.12
  • HIC++ v3.3 - 8.4.4

Click here for references