Can something similar to &x=&y be accomplished in C

Tom St Denis tstdenis@ellipticsemi.com
Thu Aug 30 11:13:00 GMT 2007


Jim Stapleton wrote:
> Thanks, I was more concerned with performance (an extra op or two each
> access), than with ease of use.
>   

As the others pointed out &x references are actually implemented via
pointer deferences.  C++ isn't some magical language, it's bound by the
same rules of the architecture as C.  So to read/write that reference
you have to work through a pointer.

Note that GCC may alias *X to a register during it's computation.  For
example,

int func(int *x, int *y)
{
   *x = (*x * *y) + *y - (*y >> 2) + (*y << 4);
   return *x;
}

produces this X86 code with GCC 4.1.2 (-O3 -fomit-frame-pointer)

func:
.LFB2:
        movl    (%rsi), %edx
        movl    %edx, %eax
        movl    %edx, %ecx
        imull   (%rdi), %eax
        sarl    $2, %ecx
        leal    (%rdx,%rax), %eax
        sall    $4, %edx
        subl    %ecx, %eax
        addl    %edx, %eax
        movl    %eax, (%rdi)
        ret


As you can see x and y are pointed to by rsi and rdi.  rsi get loaded
into edx, and reused.  And now with using C++ ref's you get

_Z4funcRiS_:
.LFB2:
        movl    (%rsi), %edx
        movl    %edx, %eax
        movl    %edx, %ecx
        imull   (%rdi), %eax
        sarl    $2, %ecx
        leal    (%rdx,%rax), %eax
        sall    $4, %edx
        subl    %ecx, %eax
        addl    %edx, %eax
        movl    %eax, (%rdi)
        ret

Notice some similarities?

Tom



More information about the Gcc-help mailing list