Both C99 and C++98 have about the same type checking strictness. Although
the original K&R C has very loose type checking, the newer standards
make C a strongly-typed language.
Generally speaking, C and C++ does not let you use one type when another
type is expected. The exceptions to this rule can be summarized as
follows:
- for scalars (like integers, real numbers and etc.):
- It is okay to specify a scalar parameter with a smaller range
when a scalar with a larger range is expected.
- In a scalar assignment, the type of the left hand side can have a
bigger range than the type of the right hand side.
- The above exception does not work when passed by reference.
- for pointers:
- (C++ only): It is okay to specify a pointer to a subclass
when a pointer to a superclass is expected.
- (C and C++): It is okay to specify a pointer to anything when
a void pointer
(void*)
is expected.
- for all:
- It is okay to specify a non-
const
object when a
const
object is expected.
Note that C and C++ both consider the following two named structures
different:
struct X
{
};
struct Y
{
};
Despite both structures have no members (and hence structurally identical),
X
and Y
are still
considered different types.
Consequently, the following code generates a warning:
struct X *pX;
struct Y *pY;
// ...
pX = pY;
Copyright © 2006-08-29 by Tak Auyeung