1

Here is the defintion of my function:

char *strsub(char const *s, unsigned int start, size_t len){
   blabla
   blabla
   while (len > 0)
   {
      len--;
      cpy[start++] = s[start++];
   }
}

When I try to compile I get this error:

error : multiple unsecquenced modifications to start -Werror , -Wunsequenced

I don't understand that error at all.

P.P
  • 117,907
  • 20
  • 175
  • 238
Dylan Uzan
  • 21
  • 2

3 Answers3

5
cpy[start++] = s[start++];

In this you modify start more than once without an intervening sequence point. This is undefined behaviour. Your compiler helpfully points that out.

If you want to copy the bytes from one location to another you probably don't want to modify start twice anyway. So, do:

while (len > 0)
{
   len--
   cpy[start] = s[start];
   start++;
}

Please read:

Undefined behaviour and sequence points

A Guide to Undefined Behavior in C and C++

What Every C Programmer Should Know About Undefined Behavior

for more informationn on this subject.

Community
  • 1
  • 1
P.P
  • 117,907
  • 20
  • 175
  • 238
3

Is this

cpy[start++] = s[start++];

supposed to increment start once or twice? While you might know the answer, the compiler scratched its head.

There might be languages where this has a defined result (usually by order of evaluation from left to right), but C is not one of them (it's undefined behavior).

The word unsequenced in the error message refers to the C language concept of sequence points. In the shown expression there is only one sequence point -- the semicolon. But there are two post-increments. Which one should be executed first? C leaves this open^Wundefined.

Jens
  • 69,818
  • 15
  • 125
  • 179
0

Quoting directly from C11, chapter §6.5.16, Assignment operators,

[...] The side effect of updating the stored value of the left operand is sequenced after the value computations of the left and right operands. The evaluations of the operands are unsequenced.

That means, in your code,

cpy[start++] = s[start++];

you're making attempt to modify the value of start more than once without having a sequence point in between, which is plain wrong and will invoke undefined behavior.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261