Hello All,
I have been writing C programs since 5 years. Just wondering, what happens when we typecast any variable.?
I would appreciate your comments.
Thanks,
Hello All,
I have been writing C programs since 5 years. Just wondering, what happens when we typecast any variable.?
I would appreciate your comments.
Thanks,
Typecasting is just an instruction to the compiler to;
1) not reject (i.e. fail to compile) an obviously invalid type conversion;
2) not complain (i.e. give a warning or error message) about a potentially invalid type conversion.
In both cases typecasting is a means for the programmer to tell the compiler "don't complain, I know what I'm doing". The most common causes of problems associated with typecasting come in when the programmer really doesn't know what he or she is doing (eg casting of pointer types between incompatible types) but uses a typecast to stop the compiler complaining about an invalid operation.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
A type cast also may cause the compiler to either do a conversion from the type of the variable to another type, where that conversion may be non-trivial, as inAnother legitimate place for a type cast is when converting a void * to a known type or vica-versa, as inCode:int intval = 2; double dblval = sin((double)intval);Code:struct alpha { struct alpha *a_next; struct alpha *a_prev; int a_type; double a_value; char a_name[40]; }; struct alpha *element = (struct alpha *)malloc(sizeof(struct alpha));
Insert obnoxious but pithy remark here
>Another legitimate place for a type cast is when converting a void * to a known type or vica-versa
Only if you're using a REALLY old compiler, or C++. C has allowed implicit conversions to and from void* for a long time now, so there's really no point in using a cast in those cases. But that's my opinion. I know a bunch of people that still use the cast as a matter of style because they think it's more informative and like to type.
Interestingly enough, in practice, when I find myself in a position of trying to pass an int to a math function that expects a double, a check through preceding code usually identifies a variable that is declared as int, but should really be a double.Originally Posted by filker0
In any event, the following achieves the same as the above, with less typing.
While, literally, this does something more (it converts intval to double as required, then multiplies it by 1.0, and passes the result) very few compilers fail to optimise "intval*1.0" and treat it only as a conversion. And, if some "smart" maintainer comes along an removes the multiplication on the basis that it "doesn't do anything" their reward is a complaining compiler.Code:int intval = 2; double dblval = sin(intval*1.0);