2

In the recent post C string to uppercase in C and C++, the function:

void strupp(char* beg)
{
    while (*beg++ = toupper(*beg));
}

showed the undesirable result of 'OOBAR' when given 'foobar' with an answer explaining "there is no sequence point" in the expression. Now I have always been using

char *s1=strTo, *s2= strFrom;
while (*s2) *s1++ = *s2++;

with the understanding it means to get the value of the right part (*s2), increment s2; assign the obtained value to *s1 and increment s1. But it seems that this neither contains a sequence point so that it has always worked would be coincidence (luck), which I can't believe.

Anyone can help me and explain this?

Community
  • 1
  • 1
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41

2 Answers2

2

The outcome of

while (*beg++ = toupper(*beg));

depends on whether the LHS is evaluated first or the RHS is evaluated first.

The outcome of

while (*s2) *s1++ = *s2++;

does not depend on whether the LHS is evaluated first or the RHS is evaluated first.

That is the crucial difference. Hence, lack of a sequence point matters in the first case but does not matter in the second case.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 1
    Isn't `=` (assignment) defined as right-to-left evaluation? Shouldn't the RHS then always be evaluated before the LHS? Or is this only about when the `++` is performed? – Paul Ogilvie Oct 12 '15 at 17:27
  • 1
    The LHS is evaluated to figure out where the value of the RHS needs to be set. The RHS is evaluated to figure out what value to assign to the LHS. Hence, they can be evaluated in any order. The values are incremented as a side effect. That happens only before the next sequence point. See http://stackoverflow.com/questions/1895922/sequence-points-and-partial-order for more details. – R Sahu Oct 12 '15 at 17:38
  • More questions and answers on sequence points: http://stackoverflow.com/search?q=%5Bc%5D+sequence+points. – R Sahu Oct 12 '15 at 17:39
1

The result of your operation:

*s1++ = *s2++;

does not depend on when the increments are done. So the absense of the sequence point doesn't pose any problems.

PineForestRanch
  • 473
  • 2
  • 11