Practical, Pragmatic, C++
RSS icon Email icon Home icon
  • C++ Types 1

    Posted on April 22nd, 2009 wozname No comments

    What is a Type?

    What is a type? It’s a good question, it’s something that programmers take for granted every day. Yet we don’t step back and ponder exactly what a type is. A type is a description of how a physical representation maps to a more abstract concept. Remember that all the computer knows about, are bits, which can either be 0 or 1. Imagine a set of three bits, 010, by themselves they don’t mean anything. The computer certainly doesn’t know their meaning. So we have to give them some meaning. They could mean the number 2, which really is the simplest meaning. Alternatively they could be a set of signals or flags with each bit signalling that something is either on or off. Those are the two simplest interpretations of the bits, as a number or a set of flags.

    There is now a second level of meaning that you could attach to those bits. If they are interpreted as a set of flags, the next question is what do the flags actually represent? There is a big difference between the second bit representing that a disk is present or it signalling that the program should launch all the thermonuclear weapons. This meaning is also it’s type. The bit pattern 010 has a different interpretation depending on whether it’s set to be the DiskDriveFlags type or the WeaponsOfMassDestructionFlags type.

    If the set of bits is a number they could either be signed or unsigned, this is important because the bits 110 would have quite different interpretations if they are signed or unsigned. (Typically they would be either -2 if they are signed or 6 if unsigned.)

    We can take it up to the next level of abstraction again, what does the number actually represent? It could represent a represent a count, a magnitude, a velocity, a time or any other basic measure. Now up to the next level, what does the count represent? The number of nuclear bombs on the base or the amount of coffee remaining in the pantry? There is a big difference between the two and we don’t want to mix them up.

    So as you can see types, are very important for interpreting raw data. Without types we wouldn’t be able to make head or tail of the raw bit patterns. In general more complex types are built up of simpler types and a type can be as (conceptually) as big as you want.

    Happy Programming :)

    Leave a reply