Is there any difference between line 2 and line 3 in the following code? What does compiler do in each case?
char ch = 'A'; //line 1
int i = ch; //line 2
int j = (int) ch; //iine 3
In general, what is the difference between Casting and Conversion (in C and C++)?
Type casting is the process in which the compiler automatically converts one data type in a program to another one. Type conversion is another name for type casting. For instance, if a programmer wants to store a long variable value into some simple integer in a program, then they can type cast this long into the int.
Type casting refers to changing an variable of one data type into another. The compiler will automatically change one type of data into another if it makes sense. For instance, if you assign an integer value to a floating-point variable, the compiler will convert the int to a float.
In C programming, we can convert the value of one data type ( int, float , double , etc.) to another. This process is known as type conversion.
Type conversion is converting one type of data to another type. It is also known as Type Casting. In C#, type casting has two forms − Implicit type conversion − These conversions are performed by C# in a type-safe manner.
There's no difference in the final effect.
A cast is to use explicit, general, built-in cast notation for conversion.
Although in some cases we say "up-cast" when we mean an implicit conversion from Derived* to Base* (or from Derived& to Base&).
And in some cases one defines new cast notation.
The above definition of the terminology is just an operational definition, that is, it's not a definition where you can reason out that something is a cast. Casts are just those that are defined as casts. :-) For example, bool(x)
is a cast, while !!x
, which does the same and also is explicit notation, is not a cast.
In C++ you can and preferably should use the named casts static_cast
, const_cast
, dynamic_cast
and reinterpret_cast
, with possible exception for explicit casting of arithmetic built-in types. One reason is that a C style cast (Other*)p
, or in C++-specific notation OtherPtr( p )
, can do different things depending on context, and in particular, when the code is slightly changed the meaning of a C style cast can change. Another reason is that it's difficult to search for C style casts.
That said, the best is to avoid casts to the degree possible.
Cheers & hth.,
Both of them are conversions/casts, in line 2 it's just implicit, while on line 3 it's explicit, there's no functional difference.
End result is the same (that is both your int are valued at 65).
now, line 3 allows the reader (or whomever might have to maintain the code) - to spot the C cast; which is in my humble opinion a plus.
if this code is part of a C++ app, it would be even better to use static_cast for at least 2 reasons:
hope it helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With