Are compound literals Standard C++?

后端 未结 2 1349
暗喜
暗喜 2020-11-29 07:19

Compound Literals are a C99 construct. Even though I can do this in C++ :

#include 
using namespace std;

int main() {
    for (auto i : (flo         


        
2条回答
  •  清歌不尽
    2020-11-29 08:01

    (float[2]) {2.7, 3.1}
    

    is a C99 compound literal. Some compilers support it in C++ as an extension.

    float[2] {2.7, 3.1}
    

    is a syntax error.

    Given using arr = float[2];,

    arr {2.7, 3.1}
    

    is valid C++ that list-initializes a temporary array of two floats.

    {2.7, 3.1}
    

    is called a braced-init-list.

    Finally, for your code,

    for (auto i : {2.7, 3.1}) cout << i << endl;
    

    works equally well and is perfectly valid C++ - this constructs a std::initializer_list under the hood. If you really want floats, add the f suffix to the numbers.

提交回复
热议问题