Performs explicit type conversion
Contents |
(type-name)expression | |||||||||
where
| type-name | - | either the typevoid or anyscalar type |
| expression | - | anyexpression ofscalar type (unlesstype-name isvoid, in which case it can be anything) |
Iftype-name isvoid, thenexpression is evaluated for its side-effects and its returned value is discarded, same as whenexpression is used on its own, as anexpression statement.
Otherwise, iftype-name is exactly the type ofexpression, nothing is done (except that ifexpression has floating type and is represented with greater range and precision than its type indicates – see below).
Otherwise, the value ofexpression is converted to the type named bytype-name, as follows:
Everyimplicit conversion as if by assignment is allowed.
In addition to the implicit conversions, the following conversions are allowed:
In any case (both when executing an implicit conversion and in the same-type cast), ifexpression andtype-name are floating types andexpression is represented with greater range and precision than its type indicates (seeFLT_EVAL_METHOD), the range and precision are stripped off to match the target type.
Thevalue category of the cast expression is always non-lvalue.
Becauseconst,volatile,restrict, and_Atomic qualifiers have effect onlvalues only, a cast to a cvr-qualified or atomic type is exactly equivalent to the cast to the corresponding unqualified type.
The cast tovoid is sometimes useful to silence compiler warnings about unused results.
The conversions not listed here are not allowed. In particular,
If the implementation providesintptr_t and/oruintptr_t, then a cast from a pointer to an object type (includingcvvoid) to these types is always well-defined. However, this is not guaranteed for a function pointer. | (since C99) |
Note that conversions between function pointers and object pointers are accepted as extensions by many compilers, and expected by some usages of POSIXdlsym function.
#include <stdio.h> int main(void){// examining object representation is a legitimate use of castconstdouble d=3.14;printf("The double %.2f (%a) is: ", d, d);for(size_t n=0; n!=sizeof d;++n)printf("%02X ",((unsignedchar*)&d)[n]); // edge casesstruct S{int x;} s;// (struct S)s; // error; not a scalar type, even though// casting to the same type does nothing(void)s;// okay to cast any type to void}
Output:
The double 3.14 (0x1.91eb851eb851fp+1) is: 1F 85 EB 51 B8 1E 09 40
C++ documentation forexplicit type conversion |