Type casting changes a value from one type to another using explicit syntax, allowing different operations or storage.
Execution Sample
C++
int main() {
double pi = 3.14;
int intPi = (int)pi;
return intPi;
}
This code converts a double value 3.14 to an int by cutting off the decimal part.
Execution Table
Step
Variable
Original Value
Cast Type
Result after Cast
Explanation
1
pi
3.14 (double)
-
3.14 (double)
Initial double value assigned
2
intPi
3.14 (double)
int
3 (int)
Cast double to int truncates decimal
3
return
intPi
-
3
Return the integer value
4
-
-
-
-
Program ends
💡 Program ends after returning the casted integer value 3
Variable Tracker
Variable
Start
After Cast
Final
pi
3.14 (double)
3.14 (double)
3.14 (double)
intPi
uninitialized
3 (int)
3 (int)
Key Moments - 3 Insights
Why does casting from double to int remove the decimal part?
Casting from double to int truncates the decimal part instead of rounding, as shown in step 2 of the execution_table where 3.14 becomes 3.
Is the original variable 'pi' changed after casting?
No, 'pi' remains a double with value 3.14. The cast creates a new int value in 'intPi' as shown in variable_tracker.
What happens if you cast an int to a double?
Casting int to double converts the integer to a floating-point number with decimal zero, e.g., 3 becomes 3.0, but this example shows double to int.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'intPi' after casting?
A3.14
B3
C0
D4
💡 Hint
Check step 2 in the execution_table where 'intPi' is assigned after casting.
At which step does the decimal part get removed?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Explanation' column in execution_table for when casting happens.
If we changed the cast to (float) instead of (int), what would 'intPi' hold?
A0
B3.14 (float)
C3 (int)
DError
💡 Hint
intPi is an int variable, so even casting to float first, it truncates the decimal to 3.
Concept Snapshot
Type casting in C++ changes a value's type explicitly.
Syntax: (target_type) value or static_cast<target_type>(value).
Casting double to int truncates decimals.
Original variable stays unchanged.
Useful to convert types for operations or storage.
Full Transcript
This example shows type casting in C++. We start with a double variable pi holding 3.14. We cast it to int using (int)pi, which removes the decimal part and stores 3 in intPi. The original pi remains 3.14. The program returns intPi which is 3. This shows how casting changes the type and value representation explicitly.