6E. Type Checking

A C++ compiler performs type checking, which checks whether the program uses functions and operators sensibly.

For example, C++ allows you to add two numbers, but not to add two strings. (C++ differs from Java in that respect.) If you write

  const char* a = "I have ";
  const char* b = "two cats";
  const char* s = a + b;
you will get a type error. When I use g++ to compile a short program p1.cpp that contains the above statements, I get the following error message.
p1.cpp:9:17: error: invalid operands of types 'const char*' and 'const char*' to binary 'operator+'

Type checking with function calls

The sqrt function computes the square root of a number. Expression sqrt("four") leads to a type error. Similarly, since sqrt yields a real number, statement

  char* s = sqrt(24.0);
is a type error; you cannot store a real number into a variable that is supposed to hold a string.

The printf function requires its parameter to be a string. (Note the difference between printf and the Java System.out.print function.) Statements

  int n;
  …
  printf(n);
lead to a type error when compiled.

Type errors are surprisingly common. The more software you write, the more type errors you will make. It goes with the territory.

Type checking is incredibly valuable to a programmer. With it, you can be sure that you have not made one kind of error anywhere in a large piece of software.

Manual type checking

Whenever you write a function definition, think about types. Make sure that type information is consistent.

Exercises

  1. What is a benefit of type checking? Answer

  2. Recall that a string has type const char*. Suppose that function test is defined as follows. Its body is left out.

      int test(const char* str, int n)
      {
        ...
      }
    
    What is wrong with each of the following statements?
    1. int n = test(20); Answer

    2. int n = test(20, "kangaroo"); Answer

    3. test(2, 3); Answer

    4. test(const char* "kangaroo", int 30); Answer

    5. test("x", 10, 20); Answer

    6. int n; test("x", n); Answer

  3. Suppose that check is defined as follows.

      void check(int k)
      {
        printf("%10i", k);
      }
    
    What is wrong with each of the following statements?
    1. printf("%10i", check(50)); Answer

    2. int x = 25; check(int x); Answer

    3. int x; check(x); Answer

    4. check("10", 10); Answer