5D. 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.


Exercises

  1. What is a benefit of type checking? Answer