The result of this operation is not an lvalue.
The result of this operation is an lvalue if type is
a reference; in all other cases, the result is an 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 will hold
an object of the size of its argument. The statement int*
myArray = (int*) malloc(10 * sizeof(int)) does the following:
In C++ you can also use the following
in cast expressions: Function-style notation converts the value of expression to the type type:
expression( type )
#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;
}
The following is the output of the above example: x1 = 98 x2 = 98 x3 = 98The 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.
(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))
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.
Casting to a union type is the ability to cast a union member to the same type as the union to which it belongs. Such a cast does not produce an lvalue, unlike other casts. The feature is supported as an extension to C99, implemented to facilitate porting programs developed with GNU C.
#include <stdio.h>
union foo {
char t;
short u;
int v;
long w;
long long x;
float y;
double z;
};
int main() {
union foo u;
char a = 1;
u = (union foo)a;
printf("u = %i\n", u.t);
}
The output of this example is: u = 1
int main() {
union u_t {
char a;
short b;
int c;
union u2_t {
double d;
}u2;
};
union u_t U;
double dd = 1.234;
U.u2 = (union u2_t) dd; // Valid.
printf("U.u2 is %f\n", U.u2);
}
The output of this example is: U.u2 is 1.234
struct S
{
int a;
};
union U {
struct S *s;
};
struct T {
union U u;
} t[] = {
{(union U)&s}
};