In C, if I cast & dereference a pointer, does it matter which one I do first?

前端 未结 6 1758
南旧
南旧 2020-12-08 05:39

In C, you can cast both simple data types like int, float, and pointers to these.

Now I would have assumed that if you want to convert from

6条回答
  •  离开以前
    2020-12-08 06:02

    The following says get the float at pf and convert it to an integer. The casting here is a request to convert the float into an integer. The compiler produces code to convert the float value to an integer value. (Converting float values to integers is a "normal" thing to do.)

    int i1 = (int) (*pf);
    

    The following says first FORCE the compiler to think pf points to an integer (and ignore the fact that pf is a pointer to a float) and then get the integer value (but it isn't an integer value). This is an odd and dangerous thing to do. The casting in this case DISABLES the proper conversion. The compiler performs a simple copy of the bits at the memory (producing trash). (And there could be memory alignment issues too!)

    int i2 = *((int*) pf);
    

    In the second statement, you are not "converting" pointers. You are telling the compiler what the memory points to (which, in this example, is wrong).

    These two statements are doing very different things!

    Keep in mind that c some times uses the same syntax to describe different operations.

    =============

    Note that double is the default floating point type in C (the math library typically uses double arguments).

提交回复
热议问题