19.5.1. Exercises: Signed and Unsigned Integral Types

You be the computer.

[ fromfile: twoscomplement.xml id: None ]

For Example 19.4, Example 19.5, and Example 19.6, simulate the action of the computer as it executes the given code and specify what you think the output will be. Then compile and run the code yourself to see if your output is correct. If you disagree with the computer, try to explain why.

  1. Example 19.4. src/types/tctest1.cpp

    #include <iostream>
    using namespace std;
    int main() { 
      unsigned n1 = 10;
      unsigned n2 = 9;
      char *cp;
      cp = new char[n2 - n1];
      if(cp == 0)
        cout << "That's all!" << endl;
      cout << "bye bye!" << endl;
    }
    
    

  2. Example 19.5. src/types/tctest2.cpp

    #include <iostream>
    using namespace std;
    
    int main() {
      int x(7), y = 11;
      char ch = 'B';
      double z(1.34);
      ch += x;
      cout << ch << endl;
      cout << y + z << endl;
      cout << x + y * z << endl;
      cout << x / y * z << endl;
    }
    
    

  3. Example 19.6. src/types/tctest3.cpp

    #include <iostream>
    using namespace std;
    
    bool test(int x, int y)
    { return x / y; }
    
    int main()
    { int m = 17, n = 18;
      cout << test(m,n) << endl;
      cout << test(n,m) << endl;
      m += n;
      n /= 5;
      cout << test(m,n) << endl;
    }
    
    

  4. It is generally a bad idea to mix signed and unsigned numbers in any computation or comparison. Predict the output of running Example 19.7.

    Example 19.7. src/types/unsigned.cpp

    #include <iostream>
    using namespace std;
    int main() {
      unsigned u(500);
      int i(-2);
      if(u > i)
        cout << "u > i" << endl;
      else
        cout << "u <= i" << endl;
      cout << "i - u = " << i - u << endl;
      cout << "i * u = " << i * u << endl;
      cout << "u / i = " << u / i << endl;
      cout << "i + u = " << i + u << endl;
    }