Search code examples
visual-c++auto

Using "auto" to set a literal number as "INT_PTR"


Example:

void CAssignSelectedColumnDlg::SaveActionListToRegistry()
{
    const auto iSize = m_aryPtrActionColumnData.GetSize();
    for (INT_PTR i = 0; i < iSize; i++)
    {
    }
}

If I use auto i it will make an int instead of a INT_PTR. (GetSize(0) returns an INT_PTR). It is possible to somehow specify the value (0) is meant to be a INT_PTR without specifying the variable type? Does that make sense?

Eg: for(auto i = 0ip ...).


Solution

  • According to https://learn.microsoft.com/en-us/windows/win32/winprog/windows-data-types

    INT_PTR

    A signed integer type for pointer precision. Use when casting a pointer to an integer to perform pointer arithmetic.

    This type is declared in BaseTsd.h as follows:

    #if defined(_WIN64) 
      typedef __int64 INT_PTR; 
    #else 
      typedef int INT_PTR;
    #endif
    

    Are you writing for one specific configuration? Then you can use Integer literal

    If you are building for both 32- and 64-bit configurations, I am afraid you need to specify a type as INT_PTR.

    Alternatively, you can use User-defined literals

    UPDATE:

    This works for me (in case you haven't got it yet):

    #include <Windows.h>
    INT_PTR operator "" _ip(unsigned long long x) {
        return static_cast<INT_PTR>(x);
    }
    
    int main() {
        auto x = 1_ip;
    }