Recently, while I was writing a brief introduction to C for Fortran programmers, one of said Fortran programmers asked me about type casting.
To him, it did not really make sense that in C you have to explicitly cast variables instead of having the compiler do it for you automatically.
I actually had a bit of hard time making my point that this is good thing because it helps in avoiding unintentional errors.
How would you justify this?
C does not need casts. Conversions are mostly done automatically at compile time.
This works and is idiomatic C
#include <stdio.h>
int main(void) {
double x;
int i;
x = 42; /* automatically convert `int` to `double` */
i = x; /* automatically convert `double` to `int` */
printf("%f\n", i * 1.0); /* automatically convert `int` to `double` */
printf("%d\n", (int)x); /* explicit conversion needed */
return 0;
}
Too many casts in a program indicate the programmer was (probably) using a C++ compiler to compile a C source file. Some (many??) uses of casts are just plain wrong.
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