Download presentation
Presentation is loading. Please wait.
1
Casting Converting types
2
Type Conversion Implicit type coercion: when value of one type is automatically changed to another type Your code: double y = 3.0 * 5; Computer does: double y = 3.0 * 5.0;
3
Cast Cast : explicit type conversion "Turn this type into that type"
Use static_cast operator: static_cast<dataTypeName>(expression) dataTypeName : what you want to end up with expression : value you want to change
4
Cast C++ static_cast examples:
Used to force int double double y = static_cast<double>(4) Used to force double int int x = static_cast<int>(4.9) x = 4 No warning
5
Order of Ops static_cast comes:
After ( ) Before *, /, % Examples: static_cast<double>(2) / 3 / 3 … static_cast<double >(2 / 3) static_cast<double >(0) 0
6
Cast & Assignment Casting does not modify a variable: int x = 2; static_cast<double>(x); //Does nothing! Use or store value int x = 2; double xDub = static_cast<double>(x); or double z = 5.6; int zWhole = static_cast<int>(z);
7
Reasons for cast Have two integer values want decimal answer int x = 2, y = 3; double z = static_cast<double>(x) / y; Have decimal value, want an integer value Does not round up! Truncates! double avgStudents = 23.8; int classSize = static_cast<int>(avgStudents);
8
C style static_cast is C++ only
C has two versions of casting: double x = 5.2; int wholeX = (int)x; OR int wholeX = int(x); //real old school Why C++ version Type checking Easier to spot
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.