|
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+'
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.
Whenever you write a function definition, think about types. Make sure that type information is consistent.
If you pass an integer parameter to a function, does that function expect an integer parameter?
If you store the result returned by a function into a variable of type int, does that function return a result of type int?
If you pass a function two parameters does that function take exactly two parameters, not one and not three?
What is a benefit of type checking? Answer
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?
Suppose that check is defined as follows.
void check(int k) { printf("%10i", k); }What is wrong with each of the following statements?
|