Pointer Conversions
In most cases when we use an array, the array is automatically converted to a pointer to the first element:
- int ia[10];
- int* ip = ia;
The exceptions when an array is not converted to a pointer are: as the operand of the address-of (&) operator or of sizeof, or when using the array to initialize a reference to the array. We’ll see how to define a reference (or pointer) to an array
in Section 7.2.4 (p. 240).
There are two other pointer conversions: A pointer to any data type can be converted to a void*, and a constant integral value of 0 can be converted to any pointer type.
因此 char* p = false; 是合法的语句,而 char* p =true; 是非法的,因为 false提升为int 之后的值是0。
Conversions to bool
Arithmetic and pointer values can be converted to bool. If the pointer or arithmetic value is zero, then the bool is false; any other value converts to true:
- if (cp)
- while (*cp)
Here, the if converts any nonzero value of cp to true. The while dereferences cp, which yields a char. The null character has value zero and converts to false. All other char values convert to true.
Arithmetic Type and bool Conversions
Arithmetic objects can be converted to bool and bool objects can be converted to int. When an arithmetic type is converted to bool, zero converts as false and any other value converts as true. When a bool is converted to an arithmetic type, true becomes one and false becomes zero:
- bool b = true;
- int ival = b;
- double pi = 3.14;
- bool b2 = pi;
- pi = false;
Conversions and Enumeration Types
Objects of an enumeration type (Section 2.7, p. 62) or an enumerator can be automatically converted to an integral type. As a result, they can be used where an integral value is required—for example, in an arithmetic expression:
-
- enum Points { point2d = 2, point2w,
- point3d = 3, point3w };
- const size_t array_size = 1024;
-
- int chunk_size = array_size * pt2w;
- int array_3d = array_size * point3d;
The type to which an enum object or enumerator is promoted is machine-defined and depends on the value of the largest enumerator. Regardless of that value, an enum or enumerator is always promoted at least to int. If the largest enumerator does not fit in an int, then the promotion is to the smallest type larger than int (unsigned int, long or unsigned long) that can hold the enumerator value.