Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) local variable

 

A local variable is a variable that has a limited scope.

 

In the example below, there are three different local variables called 'x'. In the function A, x is local to this function and exists after it definition. In the function B, x is a function argument local to this function. In main, x is local to this function and has nothing to do with the other x's.

 

#include <iostream>

void A()
{
  int x = 3;
  //Do something with x
}

void B(const int x)
{
  //Do something with x
}

int main()
{
  int x = 0;
  //Do something with x
}

 

Declare variables as locally as possible [1].

 

Compare the speed of local versus global variables.

 

 

 

 

 

References

 

  1. Herb Sutter, Andrei Alexandrescu . C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Item 18: 'Declare variables as locally as possible'.

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict