You are here:



i have just begun to delve into programming.  i am currently reading an excellent beginners book, but i just can't wrap my mind around the whole variable thing.  could you tell me what they do, are they necessary in programming, etc?
thank you so much

In programming languages like C++ variables are things that can hold a variety of values, and the value they hold may be modified during their life time - that is the value a variable hold may vary! Without them we cannot calculate values, compute new values, make decisions based on values that vary during program execution etc.

Consider this snippet of C++ code:

   // create a variable of type int (an integer) called a
   // that is initialised with the value 10:
   int a = 10;

   a = 20; // change the value of a to 20

   // create a variable of type int (an integer) called b
   // that is initialised with the value 40:
   int b = 40;  

   // perform a simple calculation on b and store the result in a
   a = b * b; // set a to the value of b squared
         // (i.e. 40 squared, 1600)

   std::cout << b << " squared equals " << a << '\n';

Here I show the creation and use of two variables, a and b.

C++ is a (fairly) strongly typed language. This means that variables have a specific type. The type defines the way values of the variable are represented (in computer memory) and what sort of operations apply to the variable (such as arithmetic operations like +, -, /, * (multiply) etc.) and what such an operation means for that type of variable (that is, how it should be performed).

For the variables a and b in my example I have chosen to use the C++ built-in type int, an integer type. C++ has several such types. Most come in two flavours: signed and unsigned. A signed integer has a representation that allows negative values to be used. An unsigned integer type does not allow for negative numbers to be represented. I chose a plain int type which defaults to being a signed integer type.

So I create a variable called a of int type and set its initial value to 10. Then I immediately change it to 20 in the next statement, showing that variables can have their values modified.

Next I create a second integer variable called b, initialised to 40. Then I set a to be the value of b squared (that is b multiplied by itself), i.e. 40 * 40 or 1600. Note that computer programming languages often use * as the operator for multiply as X could be confused with the name of something in most such languages (e.g. some variable called X).

Finally I print out the values of b and a together with some helpful text. The output should be:

   40 squared equals 1600

Now combine this with the facility to loop and we can write something

   int const MaxValue(40);

   for ( int b(0); b < MaxValue; ++b )
       std::cout << b << " squared equals " << b * b << '\n';

Here I have done away with the variable a. The variable b is now used as a loop variable defined, tested and updated within a for loop statement (see your C++ text for details of for loops). In this case b starts out as zero, the statements within the { and } are repeated until the value of b is no longer less than (< means less than) MaxValue. MaxValue is a constant variable (der!!). That is it is a variable that we have qualified to be constant. The compiler will not let us just change the value of such a const qualified variable.

Note: This rather odd way of looking at things came about because originally C, from which C++ evolved, had no concept of const, it does now but I think it grabbed the idea from (early) C++! Hence first we had variables then C++ added the facility to make them constant.

Notice that I use the more C++ style of initialising variables for both MaxValue and b by passing in the initial value in (). Using the var = initial_value syntax is a hangover from C that C++ inherits [although some (broken) compilers have difficulty with the C++ syntax in certain situations! Remember compilers are software applications and thus have limitations and bugs!].

The reason for using a named constant like MaxValue is that such names impart more meaning to readers of your code than just a number. Also if such a value needed to be used elsewhere then changing it means only changing it in the constant definition and not trying to track down all the places the number to be changed is used - and then trying to determine if this use of say 40 is the same max value usage we are updating!!

Anyhow back to the for loop. After each execution (or iteration) of the loop body (the bits between { and } ) the ++b statement is executed. ++ is another operation that applies to integer types. It means add one to the variable. So in short the loop executes the loop body while b is 0, 1, 2, ..., 37, 38, 39. When at the end of the iteration where b is 39 the ++b update takes b to 40 and then we find b < MaxValue is no longer true. At this point the loop finishes and execution continues on to whatever statements follow the closing brace (the } ) of the loop body.

The upshot is that the:

       std::cout << b << " squared equals " << b * b << '\n';

statement is executed 40 times with b having the value 0, 1, 2, ..., 37, 38, 39

Thus we would expect the output to look like:

   0 squared equals 0
   1 squared equals 1
   2 squared equals 4
   3 squared equals 9
   37 squared equals 1369
   38 squared equals 1444
   39 squared equals 1521

So now by using variables we are doing more significant work. Finally, just as we can use output facilities such as writing to the C++ std::cout stream, we can use input facilities to read user input into variables thus:
   int b(0);
   std::cout << "Enter an integer number: ";
   std::cin >> b;
   std::cout << b << " squared equals " << b * b << '\n';

In this version we ask the user for the value of b, and then display the square of that number. [note: we can also read and write from and to files and other things].

A word of warning: none of my code examples have been tested or even compiled so I may have left in some typos - sorry if this is the case! I also do not show whole programs - the fragments shown are for example purposes only. They also lack things like error checking that more serious code would require.

Oh, and in the last example entering a too large (or to largely negative) a value will not produce the expected result. This is because the representation of the int type is a fixed size and cannot therefore handle values up to infinity - in fact for a typical 32-bit compiler the C++ in type is a signed 32-bit quantity. This means that it can handle values from approximately -2 billion to +2 billion. This means that entering numbers much above the square root of 2 billion (around 45000) will cause incorrect outputs (I think values above 46340 will cause problem if I hit the right keys on the MS Windows calculator accessory).

Finally, here is a function from an old answer I have hanging around that does something a bit more useful then computing squares of numbers, see if you can spot the variables (or in more of a C++ style of speaking, objects), and notice the 'special variables' num and base that are passed to the function as the function's parameters:

#include <iostream>
#include <vector>

// InterativeDisplay :  Iteratively displays the digits of num in the
//          requested base.
// parameters:
//    num          unsigned integer value to be displyed
//    base          the base in which to display num   

void InterativeDisplay( unsigned int num, unsigned int base )
// DIGITS[n] produces the character to display for a digit value between
// 0 and 35 decimal.
   char const DIGITS[]="0123456789abcdefghijklmnopqrstuvwxyz";

// Check base in range
   if ( base < 2 || base > 36 )
       std::cout << "Expected base value between 2 and 36..." << std::endl;

// Use vector as stack for the digits
   std::vector<char> digitStack;

// Push non-unit digits onto digitStack
   while ( num >= base )
        digitStack.push_back( DIGITS[num % base] );
        num /= base; // reduce num for next digit
// num is now in units range and is the value of the most significant digit,
// which we display first (left most).
   std::cout << DIGITS[num];

// Now pop and display the digits off the stack in reverse order...
   while ( !digitStack.empty() )
       std::cout << digitStack.back();


Hope this gives some idea of what variables are and why they are important! Please ask a follow-up if you still are having trouble. Trying to get you the "Ah! Of course!" point remotely like this for this type of thing can be difficult!  


All Answers

Answers by Expert:

Ask Experts


Ralph McArdell


I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.


My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at


©2017 All rights reserved.

[an error occurred while processing this directive]