Search code examples
cpointersassigntype-equivalence

The following assignment only causes a warning. What does this say about how C treats type equivalence?


The following assignment only causes a warning. What does this say about how C treats type equivalence?

int *iptr;
float *fptr;
float fval;
fval = 0.0;
fptr = &fval;
iptr = fptr;

In particular, I'm referring to the assignment in the last line of the above snippet of code; namely,

iptr = fptr;

Solution

  • It says more about the behavior of the compiler you're using than about C, though the compiler's behavior is (unfortunately IMHO) permitted by the C standard.

    The types int* and float* are distinct, and the language defines no implicit conversion between them.

    Attempting to assign one to the other without a cast (i.e., an explicit type conversion) is a constraint violation, which means that a compiler is required to issue a diagnostic message.

    The C standard does not require such a diagnostic to be fatal. By issuing a warning, your compiler has done its job as far as the C standard is concerned. It could, with equal validity, have rejected your program (and in my opinion that would have been more user-friendly). But either behavior is conforming.

    You can probably invoke your compiler in a way to make it treat this as a fatal error. For example, if you're using gcc the -pedantic-errors option (along with an option to specify which version of the C standard to use) should do the trick.

    If you really want to perform that assignment (with all the risks that entails), you can use a cast:

    iptr = (int*)fptr;
    

    In addition to (probably) turning off the compiler warning, a pointer cast should act as a reminder that you're doing something tricky, and it may blow up in your face if you don'w know exactly what you're doing.