Not casting pointers in C can cause problems?

前端 未结 6 1697
梦谈多话
梦谈多话 2021-02-07 15:21

Yesterday I was in class, and at some point the instructor was talking about C code. He said:

What is the purpose of making a pointer cast in C? The only

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 15:47

    Not casting pointers in C can cause problems?

    There is no implicit conversion between pointer types in C (as there are for example between arithmetic types) - with the exception with void * type. It means C requires you to cast if you want to convert a pointer to another pointer type (except for void *). If you fail to do so an implementation is required to issue a diagnostic message and is allowed to fail the translation.

    Some compilers are nice enough (or pervert enough) to not require the cast. They usually behave as if you explicitly put the cast.

     char *p = NULL;
     int *q =  NULL;
    
     p = q;  // not valid in C
    

    In summary you should always put the cast when converting pointers to pointers for portability reasons.

    EDIT:

    Outside portability, an example where not casting can cause you real problems is for example with variadic functions. Let's assume an implementation where the size of char * is larger than the size of int *. Let's say the function expects the type of one argument to be char *. If you want to pass an argument of int *, you then have to cast it to char *. If you don't cast it, when the function will access the char * object some bits of the object will have an indeterminate value and the bevahior will be undefined.

    A somewhat close example is with printf, if a user fails to cast to void * the argument for the p conversion specifier, C says it invokes undefined behavior.

提交回复
热议问题