Types

Up to this point, the only kind of object we have dealt with in our programs is double. Now we'll look at several other types, and as the course progresses we'll look at more and more, culminating with us defining new types of our own. I cannot stress this enough:

The idea of type is key to programming, regardless of the language.

As we discuss these types, we'll also go over some of the operations defined for those types. This list is not exhaustive.

double (and float)
We've seen doubles quite a bit already. We use double to simulate computing with real numbers (i.e. anything that can be represented on a number line). I say "simulate", because most numbers can only be approximated by a double, analogous to the way we approximate 1/3 as the 6-digit decimal 0.333333. We'd need an infinite number of digits to get 1/3 exactly, and in just the same way, the double type is limited to just approximating numbers like 1/3.

The issue of how to get good and reliable answers when we can only approximate such numbers is the concern of numerical analysis, which is an important field on the border between mathematics and computer science.

The float type is a "smaller", less accurate version of double.

operation(s)Comments
+,-,*,/all more or less work as you'd expect
cmathUse cmath for other typical mathematical operations. Remember #include <cmath>, and remember that all these operations are in the std namespace. Here is some online documentation on cmath.


int
The int stands for integers. This type is the real workhorse of computing. As with integers, there are no fractions, but unlike integers there are limits on both the positive and negative ends (in the billions on a typical PC today).

If you use a number like 65 in your program, it is interpreted as an int. If you used 65.0, on the other hand, it would be a double. (Numbers hard-coded into a program like this are called literals.)

operation(s)Comments
+,-,*all more or less work as you'd expect
/Division is tricky, since fractions aren't involved. Any fractional part leftover after division is simply chopped off (truncated). This leads to some odd "identities". For example:
  • If x is the int 5, and y is the int 2, then x/y is 2!
This will trick you at some point or another, I promise.
% This is the "modulus" operator. a % b returns the remainder when a is divided by b. So, for example, 5 % 3 is 2. The signs of numbers change the sign of the result (try 5 % -3, -5 % 3, and -5 % -3).
The % operator is surprisingly important. Please look at the Minutes and Seconds program to see an example of why!

Quick check: What's the output of the following code snippet?


cout << 1/2 << endl;
cout << 13 % 4 << endl;
The answer (Drag your mouse and see if the answer matches your guess):
0
1


char
The char stands for character. Each character may be a letter, number or strange thing (for example there is a "bell character", which causes your computer to beep!).
char literals are written inside single quotes, so for example, when you want to print out a letter a:
cout << 'a' << endl 
Unusual "characters", like tabs or newlines, use "escape codes". They are identified by a backslash. Tab is '\t', and newline is '\n'. For example, consider the following code snippet:
cout << 'a' << '\t' << 'b' << endl 
The printout of the code will be:
a	b
Operations on char's will be more important later on.

bool
Characters and integers and (approximations of) real numbers are objects that you probably expect to want to compute with. Boolean values are perhaps not as obvious to you. A boolean value is either true or false, yes or no, one or zero.
These are critical to computing because, as we'll soon discuss, much of programming comes down to decision making, and true/false - yes/no - 1/0 boolean values are our decisions. We'll discuss Boolean Logic in more detail later, but here are the basic operations.

operation(s)Comments
&&The logical AND operator. For bool's a and b, a && b is true if both are true and false otherwise.
||The logical OR operator. For bool's a and b, a || b is false if both are false and true otherwise.
!The NOT operator. For bool a, !a is false if a is true and true if a is false.

The words true and false can be used in your programs for boolean literal values.

Quick check: What's the output of the following code snippet?


cout << (true && false) << ' ' << !(false || true) << endl;
The answer (Drag your mouse and see if the answer matches your guess):
0 0 


string
The types we've seen so far (int, double, float, char, bool) are all built-in types. This means that they are part of the core language rather than part of some library. The last type we'll talk about today, the type string, is not a built-in type, it is defined in the library string. It is used for strings of characters.
We've already dealt with some string literals, for example "Hello World!", including the quotation marks, is a string literal. As long as you remember #include <string> and using namespace std;, you can use strings just like any other type. The true name of this type is std::string, but with the using statement we can drop the std::.

operation(s)Comments
+Concatenation. For example, if s is the string "Hello" and t is the string "World", then s + t is the string "HelloWorld".

Note: Strictly speaking, the literal "Hello World!" is not of string type but of some other built-in type (i.e., array of characters), about which we will learn later in this course. For now, you can safely ignore this subtlety; just be aware that the compiler will complain about this expression: "Hello" + "World". Of course, you can create a string variable from this literal, and the following code fragment will compile fine:

string s = "Hello";
string t = "World";
cout << s+t;

Other non-built-in types
In fact, there are many, many more types in C++. Even cin and cout are objects with types: cin is an object of type istream and cout is an object of type ostream. It will be a while before we discuss what these types are all about, but most things in C++ are objects with types.

The Power of Types

One of the easiest ways to see the importance of types in C++ is to watch how they affect cin. When you use cin >> x, the behavior of cin depends on the type of x. In other words, cin uses type information to do the right thing.
CodeUser InputProgram OutputUnread Input
char c;
cin >> c;
cout << c << endl;
23.005% 2 23.005%
int k;
cin >> k;
cout << k << endl;
23.005% 23 23.005%
double x;
cin >> x;
cout << x << endl;
23.005% 23.005 23.005%
string s;
cin >> s;
cout << s << endl;
23.005% 23.005% 23.005%
bool b;
cin >> b;
cout << b << endl;
23.005% 1 This results in an error state for cin. Only values of 1 or 0 with whitespace or end-of-file following will read in correctly. This, of course, doesn't fit the rules for the other type. Sigh. I'm trying to find out the rationale.
Important: Look carefully at this table, and make sure that you understand why cin did what it did based on the types of the variables into which it read.

Input and Output as Streams of Characters

Input like

Jones   3:25
Smith   4:11
seems to be spread over several lines and composed of different elements - numbers, strings, and characters. However, it is in fact just one long line of characters, and by reading data we move through this line of characters called an input stream.

Suppose, for example, we ran the code

Notes on whitespace and cin: Any string tab, space, and newline characters is called whitespace. An important feature of cin is that it skips leading whitespace before it starts reading.
string str1,str2;
int m1,m2,s1,s2;
char c1,c2;
cin >> str1 >> m1 >> c1 >> s1;
cin >> str2 >> m2 >> c2 >> s2;
with the above as input. What follows shows you this input stream, and demonstrates how we move through the input stream. The ^ carrot, shows what the "next character to be read" is. The tab character is represented by \t, and the newline character by \n.
   J  o  n  e  s  \t 3  :  2  5  \n    S  m  i  t  h  \t 4  :  1  1  \n
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
^

   J  o  n  e  s  \t 3  :  2  5  \n    S  m  i  t  h  \t 4  :  1  1  \n
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                  ^

   J  o  n  e  s  \t 3  :  2  5  \n    S  m  i  t  h  \t 4  :  1  1  \n
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                        ^

   J  o  n  e  s  \t 3  :  2  5  \n    S  m  i  t  h  \t 4  :  1  1  \n
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                           ^

   J  o  n  e  s  \t 3  :  2  5  \n    S  m  i  t  h  \t 4  :  1  1  \n
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                                 ^

   J  o  n  e  s  \t 3  :  2  5  \n    S  m  i  t  h  \t 4  :  1  1  \n
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                                                      ^

   J  o  n  e  s  \t 3  :  2  5  \n    S  m  i  t  h  \t 4  :  1  1  \n
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                                                            ^

   J  o  n  e  s  \t 3  :  2  5  \n    S  m  i  t  h  \t 4  :  1  1  \n
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                                                               ^

   J  o  n  e  s  \t 3  :  2  5  \n    S  m  i  t  h  \t 4  :  1  1  \n
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
                                                                     ^

Problems

Do You Know ...

  1. The difference between an "object" and a "type"?
  2. Why 1/2 is 0 in C++?
  3. What is a literal?