Variables in C++

1 Conversation

Like most programming languages, C++ has a number of fundamental data types which influence how its variables behave. However, C++ is considered to be a very strongly typed language, so they are somewhat more important than in some other languages - noteably Perl1.

Types of Variables

C++ supports six3 basic types of variable - fundamental variables, pointers, arrays, structures, unions and objects. The latter three are somewhat closely related, so we shall consider the former three first.

Fundamental variables are simply things like integers, floating-point numbers, characters or Boolean4 values. C++ provides a fairly wide selection of fundamental datatypes, which allows the programmer great control over what kind of data their program uses, and how much memory that data is allowed to occupy - this was especially useful in the days before virtual memory when RAM was exceedingly expensive. C++'s data types derive directly from C, so C programmers will find them almost identical, with the occasional addition.

  • int - A simple integer5 variable. Usually a value between -32,768 and 32,768, although this varies on different computer architectures.
  • long - A large integer - normally twice as big as a normal int.
  • short - A small integer - usually half as big as an int.
  • float - A simple floating-point6 number.
  • double - A large floating-point number, capable of either extra precision or storing larger values.
  • long double - A larger version of double. Useful for high-precision programs. On some systems, it takes up more than 16 bytes of memory.
  • char - A single ASCII character. Actually stored (and treated) as an integer between 0 and 255. char is one of the few datatypes that can be trusted to be the same size on all platforms - eight bits.
  • bool - A value that can be either true or false.

The table above is not a complete list, but it covers the basics. Note that there is no fundamental string type in C++. Instead, strings are handled using arrays of characters and pointers to them, or with the ANSI C++ string class, which makes things much easier.

Basic variables are declared very simply in C++: specify the datatype, and then a valid identifier.

int i; // declares an integer variable called i
char c; // declares a character variable called c7
bool bOn = true; // declares a boolean variable called bOn, and sets it to be true

Pointers

Pointers are a special kind of variable which exist only to point to the location of some other piece of data in memory. This may sound useless, but in actuality pointers are vital to such things as dynamic allocation of memory and string processing (as C programmers will be all too aware). They also provide extremely useful techniques for returning multiple items of data from functions and manipulating arrays.

Pointers are declared using the indirection operator *, and they also have a datatype, which represents the type of data they are going to point to.

int *pMyInt; // declares a pointer to an integer
char *MyString; // declares a pointer to a character - the fundamental way of handling strings

Arrays

C++ is capable of making arrays out of almost anything - basic variables, pointers, structures, objects, anything. They are declared very simply, using the [] operator to tell C++ that the variable should be an array.

int i[4]; // declares an array of integers with four elements.
char c[50]; // declares an array of characters with fifty elements.
char c[] = "Hello"; // declares an array of characters with six elements, and sets them to be 'H', 'e', 'l', 'l', 'o' and '\0'8.
int i[] = {4,5,6}; // declares an array of integers with three elements, and sets them to be 4, 5 and 6.

Accessing the elements of an array is also achieved through use of the [] operator. C++ has zero-indexed arrays, so the first element of the array is thought of as element 0, while the last element is element n-1 where n is the number of elements in the array. For example, the integer array i declared above has elements 0, 1, 2 and 3, which are accessed with i[0], i[1], i[2] and i[3] respectively. Arrays in C++ are not associative9 like those in PHP10, so they can only be indexed by integers.11

Structures

Structures are essentially a way to define brand-new, potentially complicated datatypes. They are conceptually a collection of variables - sort of like taking several variables of other types (fundamental variables, pointers, arrays, unions, classes or indeed other structures12) and putting them into a large bag or box to keep them all together. Because C++ treats structures as new datatypes, you can then declare as many instances of the structure as you like in the same way that you can declare as many Boolean variables as you like.

To define a structure, C++ provides the struct keyword which is used as in the following example.

struct Point {

  int x;

  int y;

  int z;

};

This declares a structure called Point which contains three integer variables: x, y and z. As you may have guessed, this kind of thing can be very useful for storing things like coordinates that come in pairs, triplets or whatever. They also do not have to be the same datatype, giving much more flexibility.

An instance of the structure can be declared using:

Point p;

Which is essentially the same as a normal variable declaration. To access the members of the structure, the . operator is employed. The code below sets the x, y and z members of the structure p to 3, 2, and 5 respectively.

p.x = 3;

p.y = 2;

p.z = 5;

It is worth noting that if you have a pointer to a structure instead of the structure itself, you should use the -> operator instead of .. This does the same thing, but allows the compiler to follow the pointer to find the structure, rather than expecting to find it where the pointer is, which doesn't work very well.

Unions

Unions are similar to structures in that they contain multiple variables of different types, but there is a very big difference: in a union, only one data member can be used at once. This may sound useless, but it can be very handy when storage space is limited and you know you're only going to have to store one value of a particular thing at a particular time, but that the datatype of that value might change. Because the same area of memory is used for all the members of the union, they're incapable of having different values, and only take up as much space as the largest member, plus some overhead for the union itself.13

Declaring a union is accomplished with the union keyword.

union MyUnion {

  int iValue;

  float fValue;

  char cValue;

}

As you can see, union declarations look a lot like structure declarations. However, if you assign a value to iValue, then another to fValue, and then try to read from iValue, you'll get a rather unpredictable result, so it's good to keep track of which union member you're using at any given time.

Classes

Classes are the basis of the fabled art of object-oriented programming, which is what makes C++ different to C. They are much like structures in that they contain multiple data members which can be used simultaneously, but unlike structures, they can also contain functions that work on the data. Those functions are called methods, and typically provide useful functions for whatever data the object contains - for a string class, for example, there might be methods to convert it to an integer value, or to find the position of a specific character within the string. A class representing a point in three-dimensional space might contain methods to translate it in 3D space based on a supplied vector (which could be represented by a similar or indeed identical class), or perhaps to rotate it around a specified point.

A full discussion of classes is beyond the scope of this Entry14, so I'll just cover the basic syntax here. I will not cover inheritance or any of the more complex object-oriented concepts - those are subjects for another Entry.

Classes are declared, unsurprisingly, using the class keyword.

class Point {

  int x;

  int y;

  int z;

  void rotate(Point *p);

  void translate(Point *p);

}

This class represents a point in 3D space, and has three data members to store the x, y and z coordinates. It also has two methods to rotate and translate it based on another point provided.

Classes are capable of much more sophisticated things than this - here I have not even touched on how to implement the methods, or highly useful15 things like method overloading, operator overloading, inheritance and templates. If you really want to learn, it is recommended that you obtain yourself a good C++ book from your local second-hand or remaindered bookstore as they can be hideously expensive when purchased new. Mine cost five pounds Sterling and is a very fine introduction to the modern C++ language.

1Perl2 doesn't, at first glance, seem to have more than three data types, and two of those are different kinds of arrays. It does, however, have rather a lot of them. It's just very good at pretending not to.2Perl is a very popular language used for many things, but especially good at text processing. A lot of websites run on Perl programs, including the early versions of h2g2 (the Llama series).3Some may not consider all six types to be different. I do.4true or false values, named after George Boole, the father of that particular breed of logical algebra that's also named after him.5An integer is a whole number, i.e. one without anything after the decimal point. 4 and -2937 are integers, 89.4 isn't.6A floating-point number is one that can have a fractional part (although it doesn't have to). This basically includes every number you normally encounter, like 56.9, -20 and 890.3282. It does not include complex numbers like the square root of minus one though.7Note that you don't have to call your variables things like i and c if you don't want to - in fact, it makes it a lot easier if you use more descriptive names.8The '\0' is inserted by C++, and indicates the end of the string. It does not display on the screen, but is vital so that string-handling routines know where to stop. Forgetting to allow enough memory for it when working with strings is a fairly common blunder.9Associative arrays are those that are indexed by association. In PHP, for example, instead of just using numbers to refer to array elements, you can also use strings - so you could call one element "Fred", one "Bill" and so forth. C++ can do this too, but you have to use the Map class for it. Perl also supports these, but calls them hashes.10PHP is a programming language designed entirely for writing server-side code to power websites - it's the kind of language you could easily used to write a site like h2g2 (although h2g2 is written in C++). Its name stands for "PHP Hypertext Preprocessor", a recursive acronym of a kind so popular among Open Source programmers.11If you really want an associative array, use the Map class provided with ANSI C++.12Just don't try and put a structure inside itself. The compiler won't like it, and if you think about it for a while you'll realise it's impossible.13To be perfectly honest, I've never used a union in any of my programs. They don't fit my way of thinking, although they do have their uses.14Entire books have been written on the subject of object-oriented programming, so I can hardly cover it all here.15Yes, really, I mean that.

Bookmark on your Personal Space


Conversations About This Entry

Entry

A610255

Infinite Improbability Drive

Infinite Improbability Drive

Read a random Edited Entry


Written and Edited by

Disclaimer

h2g2 is created by h2g2's users, who are members of the public. The views expressed are theirs and unless specifically stated are not those of the Not Panicking Ltd. Unlike Edited Entries, Entries have not been checked by an Editor. If you consider any Entry to be in breach of the site's House Rules, please register a complaint. For any other comments, please visit the Feedback page.

Write an Entry

"The Hitchhiker's Guide to the Galaxy is a wholly remarkable book. It has been compiled and recompiled many times and under many different editorships. It contains contributions from countless numbers of travellers and researchers."

Write an entry
Read more