A temporary array is assigned but not a temporary primary value

99 Views Asked by At

I am amazed that this C++ code is compiled:

int main()
{
    (int[10]){}[0]=15;
    return 0;
}

The equivalent assembly is

main:
        push    rbp
        mov     rbp, rsp
        mov     QWORD PTR [rbp-48], 0
        mov     QWORD PTR [rbp-40], 0
        mov     QWORD PTR [rbp-32], 0
        mov     QWORD PTR [rbp-24], 0
        mov     QWORD PTR [rbp-16], 0
        mov     DWORD PTR [rbp-48], 15
        mov     eax, 0
        pop     rbp
        ret

According to this code, an array is defined without having any name and then assigned.

Interestingly, when there is no array, the code does not compile:

int main()
{
    (int){}=15; /* <Compilation failed> */
    return 0;
}

1- Why is the first expression (maybe you call it assigning to an xvalue) legal in C++ for a temporary array but not the second one for a basic primary type? Why the language is designed this way?

2- What is the application of such a temporary array?

0

There are 0 best solutions below