3

I have this program and i'm having a very hard time understanding exactly how this function works and why does it do what it does. I think it has something to do with operation precedence, but i'm not really sure. Can anyone explain to me in steps how does this compile?

The program is this:

void s1( char dest[], char src[] )
{ int i = 0;

  while( dest[i++] = src[i++] );
}

int main()

{
char a[100]="abcdef";
char b[100]="123456";

s1(a,b);

puts(a);
puts(b);
return 0;

}

The output is: 1b3d5f 123456

Thanks a lot.

gliga bogdan
  • 143
  • 1
  • 5
  • 6
    This function works by chance. Doing `i++` twice in a single statement is unreliable. Where did you find this piece of cruft? – Fred Foo Jan 11 '14 at 13:17
  • it was in my assignment from the uni to figure out what does this functions output. – gliga bogdan Jan 11 '14 at 13:19
  • @larsmans to me, this is not a matter of chance, at each loop, it replace the destination with the source, but incrementing 2 by 2 – Thomas Ayoub Jan 11 '14 at 13:19
  • 6
    @Samoth The order of operations of the assignment `dest[i++] = src[i++]` is not specified by the standard. – Fred Foo Jan 11 '14 at 13:21
  • The correct answer is that it is impossible to determine the output because the code has undefined behaviour. See @larsman 's link. If your professor does not accept your answer, show him [this compiler warning from GCC](http://ideone.com/O0yufP). – JBentley Jan 11 '14 at 16:36

2 Answers2

-1

As larsmans said, you should not use double incrementation in a condition but the output is normal :

i = 0

{
dest[0] = src[0]; // src[0] is 1
i = i + 2; // i++ and i ++
}

i = 2

{
dest[2] = src[2]; // src[2] is 3
i = i + 2; // i++ and i ++
}

And so on...

Which explain your output is 1b3d5f...

wimh
  • 15,072
  • 6
  • 47
  • 98
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
  • This answer is wrong - the line `while( dest[i++] = src[i++] );` has undefined behaviour. [See here](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points). Also, [click here](http://ideone.com/O0yufP) to see the warning that GCC emits with the OP's code. – JBentley Jan 11 '14 at 16:35
-2

After the call to the function s1(a, b) is made...

dest = "abcdef"
src = "123456"

i++ is the post-increment of i...ie: current value of i is used, and then incremented hence in the first run of while loop, i = 0 is used... therefore, dest[0] = src[0] = 1... now i is incremented twice, since there is two i++ in the loop... now i = 2 therefore dest[2] = src[2] = 3 so on ... finally dest = 1b3d5f and src remains unchanged

Al-3sli
  • 2,161
  • 2
  • 15
  • 19
ankit_c
  • 1
  • 1
  • 1
    This answer is wrong - the line `while( dest[i++] = src[i++] );` has undefined behaviour. [See here](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points). Also, [click here](http://ideone.com/O0yufP) to see the warning that GCC emits with the OP's code. – JBentley Jan 11 '14 at 16:33