Microsoft KB Archive/329343

= You receive a C4311 compiler message when you cast a 64-bit pointer to a 32-bit variable =

Article ID: 329343

Article Last Modified on 1/5/2006

-

APPLIES TO


 * Microsoft Visual C++ .NET 2003 Standard Edition
 * Microsoft Visual C++ .NET 2002 Standard Edition

-



This article was previously published under Q329343



SYMPTOMS
When you try to cast a 64-bit pointer variable to a 32-bit integer variable or to a 32-bit long variable, you may receive the following C4311 compiler message:

warning C4311: 'type cast' : pointer truncation from ' ' to ' '

Note is the data type of the pointer variable, and   is the data type of the variable that you are casting from the pointer type.



CAUSE
This behavior only occurs when you try to cast a 64-bit pointer variable to a 32-bit integer variable or to a 32-bit long variable. This message detects 64-bit portability issues. In Microsoft Windows 32-bit operating systems, you can cast a pointer to a 32-bit integer variable or to a 32-bit long variable. However, you cannot do this in Windows 64-bit operating systems. In Windows 64-bit operating systems, the pointer variable is a 64-bit wide pointer variable. If you try to cast a 64-bit pointer to 32-bit variable, information loss may occur.



Steps to reproduce the behavior
 Start Visual Studio .NET. On the File menu, point to New, and then click Project. In Visual Studio .NET 2003, under Project Types, click Visual C++ Projects, and then click Win32 Console Project under Templates. In Visual Studio .NET 2002, under Project Types, click Visual C++ Projects, and then click Win32 Project under Templates. In the Name box, type MyProject, and then click OK. The Win32 Application Wizard dialog box appears. In Visual Studio .NET, click Application Settings, and then click Console application. Click Finish.</li> In Solution Explorer, expand all folders.</li> Right-click MyProject.cpp, and then click Open.</li>  Locate the following code in the MyProject.cpp code window: int _tmain(int argc, _TCHAR* argv[]) { </li>  Add the following code after the code that you located in step 9: long* m_pl = NULL; long m_l = (long)m_pl; </li>  Double-click stdafx.h, and then add the following header file at the beginning: On the File menu, click Save All to save all the files.</li> On the Build menu, click Build Solution to build the application.</li></ol>
 * 1) include <windows.h> </li>

Note For portability reasons, use the LONG64 data type instead of the long data type. To use the LONG64 data type, replace the code that is mentioned in step 9 with the following code: long* m_pl = NULL; LONG64 m_l64; m_l64 = reinterpret_cast<LONG64>(m_pl); With the reinterpret_cast operator, any pointer type can be converted to any other pointer type. Also, any integral type can be converted to any pointer type and vice versa.

<div class="references_section">