When is an integer<->pointer cast actually correct?

后端 未结 15 2678
北荒
北荒 2020-12-13 07:48

The common folklore says that:

  • The type system exists for a reason. Integers and pointers are distinct types, casting between them is a malpractice in the m

15条回答
  •  孤街浪徒
    2020-12-13 08:48

    One example is in Windows, e.g. the SendMessage() and PostMessage() functions. They take a HWnd (a handle to a window), a message (an integral type), and two parameters for the message, a WPARAM and an LPARAM. Both parameter types are integral, but sometimes you must pass pointers, depending on the message you send. Then you will have to cast a pointer to an LPARAM or WPARAM.

    I would generally avoid it like the plague. If you need to store a pointer, use a pointer type, if that is possible.

提交回复
热议问题