Course contentsShow
← C
Lesson 129 of 1,2192. Variables and TypesFree lesson

The cast operator `(type)`

The cast operator (type)

What you'll learn: How to temporarily force a piece of data to act like a different type using the cast operator.

The shape-shifter tool

Imagine you have a large square peg and a round hole. In the physical world, they just won't fit. In C, however, you sometimes have a "floating-point" number (like 9.99) that you need to squeeze into an "integer" variable. If you just shove it in, the compiler might get nervous and give you a warning, or it might cut off the decimal without you realizing it.

Explicit casting is like telling the compiler, "I know what I'm doing. Transform this data for a moment so it fits." You do this by placing the desired type name in parentheses directly in front of the value or variable you want to change.

Precision vs. Storage

The most common use for casting is handling math between integers and decimals. In C, if you divide two integers, the result is always an integer. For example, 5 / 2 equals 2, not 2.5. The decimal is simply discarded. If you want the precise answer, you must "cast" one of those numbers into a float.

int total_points = 15;
int games_played = 4;
float average;

// Without casting, average would be 3.0
// With casting, we temporarily treat total_points as a float
average = (float)total_points / games_played; 

// Result: 3.75

In the example above, (float)total_points tells C to treat that 15 as 15.0 just for this specific calculation. Because one number is now a float, C realizes it needs to keep the decimal places for the final result.

Why be explicit?

You might wonder why we don't just let the computer guess. Coding is about clarity. By using the (type) operator, you are leaving a trail of breadcrumbs for other programmers (and your future self). It signals that you are intentionally changing the data format—perhaps to save memory, or to satisfy a specific function's requirements—rather than making a careless mistake.

Key takeaway

Use the (type) operator to manually convert a value from one data type to another, ensuring your calculations stay precise and your intentions are clear.