Open main menu

Wikibooks β

C++ Programming/Examples/Data and Variables

< C++ Programming‎ | Examples

Data and variablesEdit

Let's write a program that will print each value that a byte can hold. How do we do that? We could write a loop that goes from 0 to 255. In our program, we can start off with a value of 0 and wait until it becomes 0 again before exiting. This will make sure we go through every value a byte can hold.

Inside your main() function, write the following. Don't worry about the loop just yet. We are more concerned with the output right now.

char b=0;
  cout << (int)b << " ";
  if ((b&15)==0) cout << endl;
} while(b!=0);

b is our byte and we initialize it to 0. Inside the loop we print its value. We cast it to an int so that a number is printed instead of a character. Don't worry about casting or int's right now. The next line increments the value in our byte b. Then we print a new line (carriage return/endl) after every 16 numbers by using the code "b&15" which uses '&', the bitwise AND operator, and the value 15 (00001111 in binary), to give the value of the lowest 4 bits, which will be 0 every multiple of 16, because 16 is 00010000 in binary, so multiplying this by something will just change the higher bits, and will leave the lower bits alone. We do this so that we can see all 256 values on the screen at once by printing 16 values per line, and so only using 16 lines, assuming 16 values will fit on one line.

If you were to run this program, you would notice something strange. After 127, we got -128! Negative numbers! Where did these come from? Well, it just so happens that the compiler must be told if we are using numbers that can be negative or number that can only be positive. These are called signed and unsigned numbers respectively. By default, the compiler assumes we want to use signed numbers unless we explicitly tell it otherwise. To fix our little problem, add "unsigned" in front of the declaration for b so that it reads:

unsigned char b=0;

Problem solved!