The cast operator is used for explicit type conversions. This operator has the following form, where T is a type, and expr is an expression:
( T ) expr
It converts the value of expr to the type T. In C, the result of this operation is not an lvalue. In C++, the result of this operation is an lvalue if T is a reference; in all other cases, the result is an rvalue.
The remainder of this section pertains to C++ only.
A cast is a valid lvalue if its operand is an lvalue. In the following simple assignment expression, the right-hand side is first converted to the specified type, then to the type of the inner left-hand side expression, and the result is stored. The value is converted back to the specified type, and becomes the value of the assignment. In the following example, i is of type char *.
(int)i = 8 // This is equivalent to the following expression (int)(i = (char*) (int)(8))
For compound assignment operation applied to a cast, the arithmetic operator of the compound assignment is performed using the type resulting from the cast, and then proceeds as in the case of simple assignment. The following expressions are equivalent. Again, i is of type char *.
(int)i += 8 // This is equivalent to the following expression (int)(i = (char*) (int)((int)i = 8))
Taking the address of an lvalue cast will not work because the address operator may not be applied to a bit field.
You can also use the following function-style notation to convert the value of expr to the type T. :
expr( T )
A function-style cast with no arguments, such as X() is equivalent to the declaration X t(), where t is a temporary object. Similarly, a function-style cast with more than one argument, such as X(a, b), is equivalent to the declaration X t(a, b).
For C++, the operand can have class type. If the operand has class type, it can be cast to any type for which the class has a user-defined conversion function. Casts can invoke a constructor, if the target type is a class, or they can invoke a conversion function, if the source type is a class. They can be ambiguous if both conditions hold.
An explicit type conversion can also be expressed by using the C++ type conversion operator static_cast.
Example
The following demonstrates the use of the cast operator. The example dynamically creates an integer array of size 10:
#include <stdlib.h> int main(void) { int* myArray = (int*) malloc(10 * sizeof(int)); free(myArray); return 0; }
The malloc() library function returns a void pointer that points to memory that will hold an object of the size of its argument. The statement int* myArray = (int*) malloc(10 * sizeof(int)) does the following
Related References