3. Objects, Types, and Values

"Fortune favors the prepared mind." -- Louis Pasteur

3.1 Input

Most programs need input to on the basis of which they perform results.The input to be read has to be placed somewhere in the computer's memory to be read by the program and is called an object.

                
                int main() {
                    cout << "Please enter your name:\n";
                    string first_name; // variable of type string
                    cin >> first_name; // read characters into first name
                    cout << "Hello" << first_name;
                }
                
                

cin adds each character typed, until a newline is entered.

3.2 Variables
Stars have a variable brightness.

A named object is called a variable and every object has a type that specifies the kind of information that can be placed in that object.

int age = 42 represents an object of type int, name "age" and value 42.

The type determines the type of operation that can be done on the variable. A statement that defines a variable is called a definition and is generally used to provide an initial value.

A compiler checks for the type of variable and makes sure that you use a variable according to its type.

3.3 Input and type
                
                 #include "std_lib_facilities.h"

                 int main() {
                     cout << "Please enter your name:\n";
                     string first_name; // variable of type string
                     int age;
                     cin >> first_name; // read characters into first name
                     cin >> age;
                     cout << first_name << age;
                  } 
                
                  

The input operation is sensitive to the type of the variable being read into. If you provided CS 2953 as an input CS will be read as type string and 2953 as type int. The reading of a string is terminated by whitespace which is either space, tab or new line. cin will keep reading the input characters until a new line is entered. After the user presses enter, the next line of code will be executed.

If in the above code the user typed 2953 CS, 2953 would be read as a string, and age would be 0.

As the user didn't provide a valid value to the int variable (there is a type mismatch in the above input), the output that would be printed is "2953 0".

A string read by >> is by default terminated by a whitespace. If we want to read more than one string, we would use something like in this example:

                int main() {
                    string first_name;
                    string second_name;
                    cin >> first_name >> second_name;
                }
                
3.4 Operations and operators
Some smooth operators.

The type of a variable determine the types of operations you can apply to it. An example:

                
                int count;
                cin >> count;
                string name;
                cin >> name;
                int c2 = count + 2; // adds an integer
                string first_name = name + "Jr"; // appends to a string
                int c3 = count − 2; // - subtracts an integer
                string second_name = name − "Jr"; // error: − isn't defined for strings
                
                

The compiler knows the operations that can be applied to each variable and can prevent many mistakes. There are some usual arithmetic operations like:

  • +
  • ÷
  • %

There are some operations which have defined functions like sqrt().

There are some operations that can be performed on strings:
+ is used to concatenate strings.
== is used to compare strings.

3.5 Assignment and initialization

The assignment operation is represented by =:
int a = 8;
string b = "alpha";
b = b + "gamma";
Initialization and assignment are two different operations done using the same operator. Initialization means assigning to an empty variable. Assignment means putting in a new value, which wipes out the old one.

3.5.1 An example: detect repeated words

You use assignment when you want to put new values in an object. Consider the following example which counts the number of repeated words in the program's input:

                    
                    int main() {
                        string previous = " ";
                        string current;
                        while (cin >> current) {
                            if (previous == current) 
                                cout << "repeated word " << current;
                            previous = current;
                        }
                    }
                    
                    

(The above example is taken from Programming: Principles and Practices Using C++ by Bjarne Stroustrup, as are most of our other examples.)

Let us analyze the program.

  1. Input is read into the variable current. The while condition means that the loop will run till there are no more characters to read.

    Note: For a string >> will read whitespace separated words and you need to terminate the loop with an end-of-input character.
    For Windows, Ctrl + Z followed by <Enter> is used to termminate the string. For Unix/Mac OS, it is Ctrl + D
  2. We compare the current value with previous value and if they are equal, we print the output. Then we store the input read in current to a variable named previous.
  3. For the first word, the input is compared with " ".
    Query: Why is previous initialized with " "?
3.6 Composite assignment operators

Incrementing a variable is so common that C++ provides a syntax for this.
Example: counter = counter + 1;counter++; Some other ways to change the assigned value to a variable are:

  • +=
  • −=
  • ÷=
  • %=
  • *=
3.6.1 An example: find repeated words

We can modify the code example from the previous section to count words and output the count for the repeated words.

                
                    int main() {
                    int number_of_words = 0;    
                        string previous = " ";
                        string current;
                        while (cin >> current) {
                           ++number_of_words;
                           if (previous == current)
                                cout << "word number " << number_of_words <<
                                    " repeated: " << current;
                            previous = current;
                        }
                    }
                
                
We start word counter at 0. Each time we see a word, we increment the counter and we print the word which is repeated and the position at which it occured.
3.7 Names
The name of an Egyptian pharaoh.

A name for a variable is used to make it easier to refer them from somewhere else in the program. A name in C++ starts with a letter and can contain only letters, digits and underscore. A variable name cannot start with a number.

Here are some invalid variable names:

  • #name       // # is not a valid character
  • var$name    // a dollar sign is not allowed in a variable name
  • spice jet      // space is not allowed
  • 2x          // a variable name cannot start with a number

Variable names shouldn't be a reserved word. The compiler will generate errors for such uses. Although an underscore is allowed as a variable name and you can start a variable with an underscore, it is better to avoid such names because the compiler has some words reserved for machine and system implementation which start with an underscore.
Variable names are case sensitive: foo and Foo are different variables. You should avoid case sensitive variable names like IF or If, which is a case variation of a reserved word. The compiler would not throw an error in such cases, but a programmer might easily get confused!

Notes:

  1. There are keywords that are reserved by C++ like if, case, while, and for, which should not be used as variable names.
  2. We should not use long variable names as they are hard to type, and make code harder to read.
  3. General practice for C++ variable names is to use underscores between words, like spice_jet.
  4. You should avoid using variable names that are all uppercase, as that use is reserved for macros.
  5. Initial letter as uppercase is used when creating user-defined types like Employee.
3.8 Types and objects
  • Type: Defines set of possible values and operation for an object.
  • Object: Holds a value of a certain type.
  • Value: The actual bits in memory, interpreted according to the type assigned.
  • Declaration: is an assignment of name to an object
  • Definition: sets aside memory for an object.

Informally, we can think of an object as a box, into which we can put data of certain type. int a = 7 means a is of type int and it can hold integer values.

As we can see from the above image [to be inserted], the string representation is a bit complex. It also holds the length of string. The memory required to store a data depends on the type of data. A bit is a unit of memory in a computer. A byte is represented by 8 bits. A char calls for 1 byte of storage. An int typically uses 4 bytes.

3.9 Type safety

A program is type safe when operations on objects are done according to the type of object. We can do certain operations which are type unsafe and C++ compilers unfortunately allow that.

Ideally a programmer should use operations that are checked by compiler for static type safety, but this causes a lot of restrictions while programmimg. With C++, a programmer should be careful while coding and should avoid such type unsafe operations.

3.9.1 Safe conversions
He's safe!

There are certain conversions between the types which can be done without compromising type safety. For example an int can be converted to a double, or a char can be converted to an int. The following are the conversions which are safe:

  • bool to char
  • bool to int
  • bool to double
  • char to int
  • char to double
  • int to double
3.9.2 Unsafe conversions

"Narrowing" conversions are unsafe: putting an object into a container too small to hold it. An example:

                            int a = 200000;
                            char c = a;
                            int b = c;
                            

b will not equal a after the above code is executed, since c isn't big enough to hold the entire value of a. Unsafe conversions include:

  • double to int
  • double to char
  • double to bool
  • int to char
  • int to bool
  • char to bool
Drill

Write a program that tests all of the unsafe type conversions listed above. For instance, initialize a double, assign it to an int, and then print out the initial value you used and the resulting value in the "narrowed" type. Convert back to the broader type, and output that value, so you can see what was lost. "Hand" this program in to your TA.

Test Yourself!
  1. What terminates input into a string?
    1. whitespace
    2. any number
    3. green screen
    4. Ctrl-C
  2. What is \n called?
    1. netline
    2. newline
    3. nerdline
    4. nexus
  3. What is an object?
    1. The definition of what the possible values are for some variable.
    2. The bits in memory at some address.
    3. a container that holds a value of a certain type.
    4. A pointer to some memory.
  4. What is a literal?
    1. A "plain" value such as 12 or "Hello."
    2. An error message to the user.
    3. Taking the value of a variable too literally.
  5. What is the difference between = and ==?
    1. The first assigns a value, the second tests for equality.
    2. The first tests for equality, the second assigns a value.
    3. They are the same: you can use the interchangeably.
  6. Which of the following is a legal variable name in C++?
    1. isalpha?
    2. is this ok
    3. number
    4. 123streetA
  7. We use a declaration of a function when we...
    1. we want to write the function body, without giving the return type or the types of the parameters.
    2. just want to state its return type and the types of its parameters, but not write the function body.
    3. just want to declare that the function exists.
  8. Which of the following is a legal variable name that, nevertheless, you should not use?
    1. iF
    2. while_
    3. Int
    4. all of the other answers
  9. Which of the following is a safe type conversion?
    1. all of these are safe
    2. int to double
    3. char to int
    4. int to bool
  10. If we convert a double value of 3.25 to an int, the problem is that...
    1. the conversion will lose the .25.
    2. it will produce a run-time error.
    3. the double number is out of the range of the int type.
Answers

1. a; 2. b; 3. c; 4. a; 5. a; 6. c; 7. b; 8. d; 9. c; 10. a;

Drill
  1. Section 3.1 contains a small C++ program. We are going to modify it to produce a form letter. Change the prompt to read "Enter the name of the person you want to write to" and change the output to "Dear first_name,".
  2. Add some introductory lines. Make 'em what you want.
  3. Prompt for a friend's name. Store it in friend_name. Add the output, "Have you seen friend_name lately?"
  4. Add a prompt to enter the recipient's age. Then add the output "I hear you had a birthday and you are now age years old!"
  5. Add conditions for age: below 0 or above 110 call simple_error() with a message of disbelief.
    Below 17, print "You are young to be at NYU!"
    Above 65, print "It's great to see senior students around campus!"
  6. Test that all possible inputs work.