Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) Variable

 

A variable is something to store data in. This data can be of any data type. The name of the variable is called its identifier. Give a meaningful name to an identifier [1].

 

Don't declare a variable until you have a value to initialize it with [2,4].

 

In the code example below, there are two variables, 'number' and 'i':

 

#include <iostream>

int main()
{
  int number = 0;
  for (int i = 0; i!=10; ++i)
  {
    number+=i;
    std::cout << i << " : " << number << std::endl;
  }
}

 

This produces the following screen output:

 

0 : 0
1 : 1
2 : 3
3 : 6
4 : 10
5 : 15
6 : 21
7 : 28
8 : 36
9 : 45

 

The scope of the variable 'number' is from the line it is declared to the end of main.

The scope of the variable 'i' is inside the for-loop.

Declare variables as locally as possible [5]

 

 

 

 

 

References

 

  1. Bjarne Stroustrup. Programming. 2009. ISBN: 978-0-321-54372-1. Chapter 5.9.1: 'Use meaningful names'
  2. Bjarne Stroustrup. The C++ Programming Language (3rd edition). 1997. ISBN: 0-201-88954-4. Item 6.5.10: 'Don't declare a variable until you have a value to initialize it with'.
  3. Bjarne Stroustrup. Programming. 2009. ISBN: 978-0-321-54372-1. Chapter 5.9.1: 'Use meaningful names'
  4. Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Paragraph 19: 'Always initialize variables'
  5. Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Paragraph 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