Chapter 5 Exercise Set 1: CPE PracticeΒΆ

  1. What is the output of the following program?

    #include <iostream>
    using namespace std;
    
    int main() {
      bool ints = sizeof(long) >= sizeof(int) && sizeof(int) >= sizeof(short);
      bool floats = sizeof(float) == 0.5 * sizeof(double);
      bool chars = sizeof(char) == 1;
      int v = ints && floats && chars;
      cout << v << endl;
    
      return 0;
    }
    
    1. True

    2. False

    3. 1

    4. 0

  2. What is the output of the following program?

    #include <iostream>
    using namespace std;
    
    int f() {
        return 1;
    }
    
    int f(int n) {
        return n + 1;
    }
    
    int f(int n, int m) {
        return n + m + 1;
    }
    
    int main() {
        cout << f() + f(0) + f(3, 4) << endl;
        return 0;
    }
    
  3. What is the output of the following program?

    #include <iostream>
    using namespace std;
    
    int f() {
        return 1;
    }
    
    int f(int n) {
        return n % 2 == 0 ? 1 : 0;
    }
    
    int f(int n, int m) {
        return n > m ? n - m : m - n;
    }
    
    int main() {
        cout << f() + f(11) + f(3, 4) << endl;
        return 0;
    }
    
  4. What is the output of the following program?

    #include <iostream>
    using namespace std;
    
    int f(int a) {
        int b = 0;
        int c = 5;
        int total = 0;
        while (--c)
            total += b;
        return total - a;
    }
    
    int f(int a, int b) {
        int c = 5;
        int total = 0;
        while (--c)
            total += b;
        return total - a;
    }
    
    int f(int a, int b, int c) {
        int total = 0;
        while (--c)
            total += b;
        return total - a;
    }
    
    int main() {
        cout << f(3, 1, 2) << f(5, 2) << f(0) << endl;
        return 0;
    }
    
  5. What is the output of the following program?

    #include <iostream>
    using namespace std;
    
    int f(char x, float y) {
        return 2 * x + y;
    }
    
    int f(float x, char y) {
        return x - y;  
    }
    
    int f(int a, int b, int c) {
        int total = 0;
        while (--c)
            total += b;
        return total - a;
    }
    
    int main() {
        char c1 = 3;
        char c2 = 5;
        cout << f(1, 4, 2) << f(c2, 2.0) << f(4.0, c1) << endl;
        return 0;
    }
    
  6. What is the output of the following program?

    #include <iostream>
    using namespace std;
    
    int f(char x) {
        return x * x;
    }
    
    int f(double g) {
        return int(g);
    }
    
    int f(int a, int b, int c) {
        int total = 0;
        while (--c)
            total += b;
        return total - a;
    }
    
    int f(double a, int b, char c) {
        return int(a + b + c);
    }
    
    int main() {
        char ch = 3;
        cout << f(2, 3, 4) << f(3.0, 1, ch) << f(1.0) << f(ch) << endl;
        return 0;
    }