Why can I implicitly convert an int literal to an int * in C but not in C++?

后端 未结 4 1812
北荒
北荒 2020-12-09 15:58

I believed that in the following code, C \"automatically casts 17 to an int *\" which, as someone recently pointed out (but did not give the reasons as to why),

4条回答
  •  醉话见心
    2020-12-09 16:04

    It has been, C has implicit conversions - in my experience pretty much from any integral type to any other integral type. Pointers in C are considered integralscalar types.

    In C++, Integral Types are defined as follows:

    Types bool, char, char16_t, char32_t, wchar_t, and the signed and unsigned integer types are collectively called integral types.48 A synonym for integral type is integer type. The representations of integral types shall define values by use of a pure binary numeration system.49 [ Example: this International Standard permits 2’s complement, 1’s complement and signed magnitude representations for integral types. —end example ]

    The only integral value that can be converted to pointer type in C++ is the null pointer constant, though technically the conversion is to a prvalue of type std::nullptr_t. (para 4.10)

    Final Note

    Instead of fixing it like this:

    int *ptoi = (int *)17;
    

    considering adding the C++-style cast:

    int *ptoi = reinterpret_cast(17);
    

    to make it clear what kind of conversion you are trying to invoke

提交回复
热议问题