Microsoft KB Archive/38218

From BetaArchive Wiki

INFO: Why pointer1++ = pointer2 Is Not Proper

Article ID: Q38218

The information in this article applies to:

  • Microsoft C for MS-DOS, versions 5.1, 6.0, 6.0a, 6.0ax
  • Microsoft C/C++ for MS-DOS, version 7.0
  • Microsoft Visual C++ for Windows, versions 1.0, 1.5, 1.51, 1.52
  • Microsoft Visual C++ 32-bit Edition, versions 1.0, 2.0, 2.1, 4.0, 5.0

SUMMARY

The following statement is not correct because the post-increment operator (++) has higher precedence than the assignment operator (=):

   pointer1++ = pointer2;

The following statement

   pointer1++ = pointer2 ;

is equivalent to the following statement:

   (pointer1++) = pointer2 ;

MORE INFORMATION

As defined by the post-increment operation, the result of evaluating the expression (pointer1++) is NOT an lvalue; therefore, (pointer1++) cannot be used as a left operand of the assignment operator.

However, a statement such as the following is correct:

   *(pointer1++) = *pointer2;

The above statement is equivalent to:

   *pointer1++ = *pointer2;

This statement is correct because although (pointer1++) is not an lvalue, it can be used for indirection and *(pointer1++) is an lvalue. It is very important to understand the difference between the value of the expression (pointer1++) and the value of pointer1. Although (pointer1++) has higher precedence in the above statements, the result of evaluating (pointer1++) has the old value that pointer1 had before the evaluation of the expression (pointer1++). Because of the side effect of the post-increment operator, the evaluation of (pointer1++) causes the value of pointer1 to be incremented by one only after the rest of the statement has been evaluated. In other words, as an address, (pointer1++) points to the same memory location as pointer1 used to. Therefore, *pointer1++ or *(pointer1++) represents the same object as *pointer1 used to.

The following example has the effect of assigning "a" to memory offset location 0x100, then incrementing ptr1 to point to memory offset 0x101:

char * ptr1 = 0x100; /* ptr1 points to memory offset 0x100 */ 

*ptr1++ = 'a';       /* ptr1 points to memory offset 0x101 */ 
Keywords          : kbLangC kbVC 
Version           : MS-DOS:5.1,6.0,6.00a,6.00ax,7.0;  WINDOWS:1.0,1.5,1.51,1.52; WINDOWS NT:1.0,2.0,2.1,4.0,5.0
Platform          : MS-DOS NT WINDOWS

Last Reviewed: August 28, 1997
© 1999 Microsoft Corporation. All rights reserved. Terms of Use.