M Sharath Hegde
M Sharath Hegde

Reputation: 483

Type casting used along with Compound assignment operator

((unsigned long long *)P)[0] += B;

Is the above Statement equivalent to: ((unsigned long long *)P)[0] = ((unsigned long long *)P)[0] + B; ?

P is defined as: int P[5];

B is defined as: unsigned long long B;

Size of int is 2 bytes.

Upvotes: 1

Views: 96

Answers (1)

P.W
P.W

Reputation: 26800

They mean the same and the assembly (for x86-64 systems) is the same as well. You can check this at the godbolt compiler explorer here which shows the assembly of the two statements.

int P[5];
unsigned long long B;

void check1() {
    ((unsigned long long *)P)[0] += B;
}

void check2() {
    ((unsigned long long *)P)[0] = ((unsigned long long *)P)[0] + B;
}

Assembly of check1:

check1:
        pushq   %rbp
        movq    %rsp, %rbp
        movl    $P, %eax
        movq    (%rax), %rdx
        movq    B(%rip), %rax
        movl    $P, %ecx
        addq    %rdx, %rax
        movq    %rax, (%rcx)
        nop
        popq    %rbp
        ret

Assembly of check2:

check2:
        pushq   %rbp
        movq    %rsp, %rbp
        movl    $P, %eax
        movq    (%rax), %rdx
        movq    B(%rip), %rax
        movl    $P, %ecx
        addq    %rdx, %rax
        movq    %rax, (%rcx)
        nop
        popq    %rbp
        ret

Upvotes: 1

Related Questions