Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting twice in one line

Tags:

c

casting

In a project I saw the following line and I did not understand the reason of casting twice.

*((MY_STRUCT_T*)(void *)cp->down.common) = *(cp->dpr);

What is the reason of casting twice? Why not casting directly to MY_STRUCT_T*?


to add more details:

typedef union download_s {
    MY_STRUCT_1_T *a1;
    MY_STRUCT_2_T *a2;
    void         *common;
} download_t;

typedef struct cp_s {
 ...
 MY_STRUCT_T *dpr;
 ...
} cp_t;
like image 343
mustafa Avatar asked Nov 10 '22 13:11

mustafa


1 Answers

If cp->down.common is void * already casting to the latter (the "inner" cast to (void *)) is needless.

This would do the job:

*((MY_STRUCT_T *) cp->down.common) = *(cp->dpr);

A different case would be if cp->down.common is declared intptr_t, then indeed going via void * (as shown in the OP) would be necessary as only void * is guaranteed to fit into intptr_t.

The C-Standard says:

[intptr_t] designates a signed integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer

like image 85
alk Avatar answered Nov 14 '22 23:11

alk