Share via


C++ small gotcha

Suppose str1 and str2 points to the same zero terminated string, will str1 and str2 be the same value after running below while loop?

while(*str1)

{

str1++;

};

while(*str2++);

Answer:

Str1 points to the terminating zero of the string. But str2 points to the memory address after the zero.

See the assembly of “while(*str2++);” will reveals how this statement work:

while(*str2++);

01043505 mov eax,dword ptr [str2]

01043508 mov cl,byte ptr [eax]

0104350A mov byte ptr [ebp-0F1h],cl

01043510 mov edx,dword ptr [str2]

01043513 add edx,1

01043516 mov dword ptr [str2],edx

01043519 movsx eax,byte ptr [ebp-0F1h]

01043520 test eax,eax

01043522 je ReverseStr+66h (1043526h)

01043524 jmp ReverseStr+45h (1043505h)

We can see it will fetch the value from the memory address pointed by str2 to eax, then increase str2 by 1 and then test if the eax is zero. The fetch and increase occurs first before the increase, thus cause str2 to point to the address after the terminating zero.

The “while(*str2++);” statement is the same as this code:

char temp;

do

{

        temp = *str3;

        str3++;

}while (temp);