C/Typecasting

From Wikiversity
< C
Jump to: navigation, search

C has the concept of data types:

int a;
float b;

When you assign b to a:

a=b;

An int is converted to a float implicitly. However, (potentially) dangerous conversions are forbidden and stopped by the compiler:

/* * means pointer, you will learn them later. 
Assigning between pointers of different types is dangerous unless their layout is compatible */
int*x;
float*y;
y=x;

Converting a float* to an int* is dangerous and will be blocked by the compiler. If you must perform this operation, use the following typecast:

y=(float*)x;

A type inside a pair of () is to force change x to a float* so that it can be assigned to y. If the compiler doesn't know how to convert, the result is unspecified. One can use casts to circumvent the type system of C.

Casts are dangerous, but sometimes needed.


Project: Topic:C
Previous: Storage Classes — C/Typecasting — Next: Variables and Expressions