I'm learning C++ on codesdope.com and I have read a document on another website, learncpp.com. But these two websites have different ways to assign values ​​to the array.

//codesdope.com

std::array<int,5> n  {{1,2,3,4,5}};
//learncpp.com

std::array<int,5> n = {1,2,3,4,5};

Which way is more accurate? Which way should I choose? What is the difference between them?

2 Answers

1
user10933809 On

Both versions have the same assembly code:

    std::array<int,5> n {{1,2,3,4,5}};

    mov     rcx, qword ptr [.L__const.main.n]
    mov     qword ptr [rbp - 24], rcx
    mov     rcx, qword ptr [.L__const.main.n+8]
    mov     qword ptr [rbp - 16], rcx
    mov     edx, dword ptr [.L__const.main.n+16]
    mov     dword ptr [rbp - 8], edx

the second style:

    std::array<int,5> n2 {1,2,3,4,5};

    mov     rcx, qword ptr [.L__const.main.n2]
    mov     qword ptr [rbp - 24], rcx
    mov     rcx, qword ptr [.L__const.main.n2+8]
    mov     qword ptr [rbp - 16], rcx
    mov     edx, dword ptr [.L__const.main.n2+16]
    mov     dword ptr [rbp - 8], edx

meaning they both have the same performance. The second is better, because it is more readable.

5
Amit G. On

Double-braces required in C++11 prior to the CWG 1270 (not needed in C++11 after the revision and in C++14 and beyond):

// construction uses aggregate initialization
std::array<int, 5> a{ {1, 2, 3, 4, 5} }; // double-braces required in C++11 prior to the CWG 1270 revision
std::array<int, 5> a{1, 2, 3, 4, 5}; // not needed in C++11 after the revision and in C++14 and beyond
std::array<int, 5> a = {1, 2, 3, 4, 5};  // never required after =

std::array reference