Why has Clang decided to allow designated initializers in C++?

拟墨画扇 提交于 2021-02-10 12:31:27

问题


I thought that designated initializers were discontinued in C++ and only worked in C. However, I came across a simple example which compiled and worked fine with clang++.

int main()
{
    int a[6] = { [4] = 29, [2] = 15 };
}

g++: https://rextester.com/AXIZ79197 (Error)

clang++: https://rextester.com/UYVHHP56966 (Works)

vc++: https://rextester.com/UCBEU10658 (Error)

Both g++ and vc++ failed to compile whereas clang++ worked just fine. It is also worth mentioning that g++ and vc++ gave different error messages. vc++ confused the designated initializers with lambda expressions. I guess I could blaim this on the fact that g++ is an older compiler, but I'm not sure tbh.

Questions:

  1. Why has clang decided to allow designated initializers when g++ and vc++ didn't?
  2. Is this just a compiler bug or is there another reason for this?

回答1:


When compiled with -pedantic these warnings are generated:

source_file.cpp:3:18: warning: designated initializers are a C99 feature [-Wc99-extensions]
    int a[6] = { [4] = 29, [2] = 15 };
                 ^~~~~~~~
source_file.cpp:3:28: warning: designated initializers are a C99 feature [-Wc99-extensions]
    int a[6] = { [4] = 29, [2] = 15 };

It is clear that clang++ by default enables c99-extensions.

This is not a bug as compilers may choose to provide additional feature. clang++ developers simply decided to keep it enabled. It is better to use -pedantic if we don't want those features.

Interestingly, while searching for related information I came upon C++ Support in Clang page where "Designated initializers" is listed as partially supported via extension for upcoming proposals:

experimental support for some proposed features of the C++ standard following C++17, provisionally named C++2a

This is the exact proposal for upcoming standard. So there might be designated initializers in future C++.



来源:https://stackoverflow.com/questions/54459635/why-has-clang-decided-to-allow-designated-initializers-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!