>
>
>
The warnings C4311 and C4312 generated …

Andrey Karpov
Articles: 671

The warnings C4311 and C4312 generated by the compiler when using the /Wp64 switch

C4311 and C4312 are ones of the most frequent warnings generated by the compiler for 32-bit code not adapted for migration to 64-bit platforms. They are generated only when you use the /Wp64 key (detecting 64-bit portability issues) intended to prepare migration of applications to 64-bit systems.

Note that the /Wp64 parameter is announced deprecated beginning with Visual C++ 9.0 since the time "to prepare for 64-bit code" has passed.

The C4311 and C4312 warnings tell you about an attempt to put a pointer into a 32-bit variable or vice versa. In a 64-bit system, these conversions are incorrect. If the code is compiled on the 64-bit platform, the pointer's value (64 bits) will be truncated if it is assigned to a variable of the int type (32 bits). This is an example of code that causes the C4311 and C4312 warnings:

   int *p;
   int a = (int)p; //C4311
   p = (int *)a; //C4312

To correct the code you should use memsize-types that can store a pointer, for instance size_t, ptrdiff_t, intptr_t, LONG_PTR, etc. This is an example of correct code:

   int *p;
   INT_PTR b = (INT_PTR)p; //OK

See the "Development of 64-bit C/C++ applications" course for detailed recommendations on creating safe 64-bit code.

If a program being developed has a short life-cycle and you do not plan to port it to the 64-bit platform, you may eliminate these warnings by disabling the /Wp64 option in the compiler settings.

Note that the /Wp64 switch carries out a rather superficial analysis and detects only crudest errors. To perform a complete analysis of your code, we recommend you to use the specialized static code analyzer Viva64 included into the PVS-Studio package. See the article "Comparing capabilities of PVS-Studio and Visual Studio 2010 in detecting defects in 64-bit programs" for comparison of diagnostic abilities of Visual C++ and Viva64.

References