0
What is typecasting in c language
Can anybody please tell me what typecasting with an example. Plz i am stuck in a program... Thanks
2 Réponses
+ 2
It is manully changing data type. For example, if you have double d = 3.65 and you need it to add to int i = 4, you can do d + i. But this gives you result 7.65. If you want to get integer result, you can do (int)d + i. This changes type of d from double to int temporary.
It is useful in many functions. If you have function func(double a, double b), you need to pass arguments of type double to it. Imagine you want to pass random numbers to it, so you generate them using rand(). You don't want them to be too big, so you do % 100 to both of them. Now you have two integers. If you try to pass them to that function, you could (or also couldn't, depends on compiler) get an error. You have to pass them this way:
func((double)(rand() % 100), (double)(rand() % 100));
Don't forget to put new type in parentheses.
+ 1
It is simple the C language is in its syntax and basic typecasting simillary to C++here in course. The diffrences are in OOP (there in no in C), so many function described in C++ course (like input/otput, strings, etc) are in C hard dirrerently..