+ 1

What is type casting in C++

15th Jul 2018, 8:09 AM
Muhammad Omer
Muhammad Omer - avatar
4 odpowiedzi
+ 3
The process of fitting one data type into another non-homogeneous data type is called typecasting. Narrowing and widening are to terms which are widely used to describe the kind of typecasting. In case of narrowing, the type with wider bit field let's say long long type stuffed into a type with narrower one like char type and data loss is inevitable. On the other hand, in the widening typecasting the opposite scenario applied to two types, thus it's safe in terms of data loss. ●● Some examples ●● unsigned char ch = 120; short int sh = 30455; int n = 1098234; long long lng = 102785633895021345; double dbl = 2.1; ch = sh; // wrap around narrowing n = sh; // widening n = lng; // overflow narrowing lng = dbl; // precision loss narrowing In C++, to force such harmful operations to be done without any diagnostic message, the scalar typecasting can be performed as The general form, destination variable = static_cast<destination type>( source variable ); example : ch = static_cast<unsigned char>( sh );
15th Jul 2018, 9:11 AM
Babak
Babak - avatar
+ 3
Cont. Fortunately, you can prevent such ill-formed operations from execution using c++'s list-initializer. double dbl {2.1}; int n {dbl}; Depends on the implementation, the compiler issues a diagnostic message -- either a warning or error.
15th Jul 2018, 9:12 AM
Babak
Babak - avatar
+ 1
"Typecasting is making a variable of one type, such as an int, act like another type, a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make 'a' function as a char." (citation: https://www.cprogramming.com/tutorial/lesson11.html?sb=tutmap )
15th Jul 2018, 8:31 AM
Janning⭐
Janning⭐ - avatar
+ 1
ok thanks
15th Jul 2018, 1:44 PM
Muhammad Omer
Muhammad Omer - avatar