In C, the result of the cast
operation is not an lvalue.
In C++, the cast result belongs to one of the following
value categories:
or
an rvalue reference to a function type
, the cast result is an
lvalue.
If type is an rvalue reference to an object
type, the cast result is an xvalue.
(prvalue)
rvalue.
#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 holds an
object of the size of its argument. The statement int* myArray
= (int*) malloc(10 * sizeof(int)) has the following steps:
In C++ you can
also use the following objects in cast expressions: type(expression)
#include <iostream>
using namespace std;
int main() {
float num = 98.76;
int x1 = (int) num;
int x2 = int(num);
int x3 = static_cast<int>(num);
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
cout << "x3 = " << x3 << endl;
}
See the output of the above example: x1 = 98
x2 = 98
x3 = 98
The integer x1 is assigned a value
in which num has been explicitly converted to an int with
the C-style cast. The integer x2 is assigned a value
that has been converted with the function-style cast. The integer x3 is
assigned a value that has been converted with the static_cast operator.For
C++, the operand of a cast expression 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.