Skip to content
Luke Shingles edited this page Mar 17, 2021 · 8 revisions

Welcome to the artis wiki!

Coding guidlines

These guidelines are intended to prevent bugs and increase the readability of the code to other users (and your future self).

Minimize variable scope

A variable is accessible to some part of the code (the scope) that depends on where it is declared. Minimizing a variable's scope means reducing the number of lines of code that can alter its value, which makes it easier for the programmer (and the compiler) to correctly reason about what the variable contains as the program runs. This is especially important when working on a multithreaded code. Globally-scoped variables (declared inside a header file) are accessible from anywhere in the program, and should be avoided where possible. Variables declared in a source file (outside of any functions) will have file scope, while variables declared inside a C++ block between { and } will exist only within their enclosing block.

for (int i = 0; i < 3; i++)
{
  printout("i = %d", i);
}

int k = 3;
printout("k = %d", i);  // syntax error: i is out of scope here

is better than

int i;

for (i = 0; i < 3; i++)
{
  printout("i = %d", i);
}

int k = 3;
printout("k = %d", i);  // logical error but valid syntax

The is because any attempt use of the i variable outside of the loop will be detected by the compiler as an error. This can prevent errors where the wrong variable has been accidentally been used in place of another one.

Clone this wiki locally