0

I'm reading CS:APP on Chapter 3 about assembly code. There is a practice problem like this: enter image description here

enter image description here

In the solution it tells me that

The compiler determines that pointer p always points to x, and hence the expression (*p)+=5 simply increments x. It combines this incrementing by 5 with the increment of y, via the leaq instruction of line 7.

And leaq 5(%rbx,%rcx),%rcxmeansCompute y += x + 5 So I rewrite the C code function according the assembly code like this:

short dw_loop (short x)
{
    short y = x / 9;
    short *p = &x;
    short n = 4 * x;
    do
    {
        y += 5 + x;
        n -= 2;
    } while (n > 0);
    return y;
};

Obviously the result will be different from the original function. So how can I understand that assembly code? I don't know why x+=y;(*p)+=5 can be translated asy+=5+x.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Ray
  • 201
  • 3
  • 6
  • It should be x += y + 5. You got it the wrong way around. – prl Dec 01 '21 at 05:02
  • The assembly code shown doesn't match the C code. In the loop, it decrements n by 1 instead of 2. It doesn't return a value. And you're right—it is changing y instead of x. – prl Dec 01 '21 at 05:19
  • 2
    See the duplicate. This is a badly written question in the book; some of the instructions in the supposed assembly output don't even exist (`idivq` with two operands). It is probably not worth trying to understand. That particular edition has exercises where the supposed compiler output is not from the compiler at all, but just some nonsense that the problem author made up. (The problems were written by a third party hired by the publisher and the book's main authors have disclaimed responsibility; don't blame them.) – Nate Eldredge Dec 01 '21 at 06:05

0 Answers0