Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explaining to someone why type casting isn't done automatically at compile time

Tags:

c

fortran

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?

like image 331
Emanuel Ey Avatar asked Dec 10 '25 09:12

Emanuel Ey


1 Answers

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.

like image 139
pmg Avatar answered Dec 13 '25 03:12

pmg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!