G++以及clang的处理VLAS定义和初始化的C++&#x24

发布于 2025-02-07 21:18:06 字数 508 浏览 0 评论 0原文

源代码如下:

using namespace std;

int main()
{
        int m = 4;
        int arr[m] = {1, 2, 3, 4};
        printf("%d\n", arr[2]);
        return 0;
}

当我使用 g ++ 编译时,它将成功编译为可执行文件。但是,当我用 clang ++ 编译时,我会收到以下错误:

VLAs.cpp:8:10: error: variable-sized object may not be initialized
        int arr[m] = {1, 2, 3, 4};
                ^
1 error generated.

测试后,我发现clang ++可以支持VLBS的定义。 ,但在初始化它们时不支持定义VLB。我想知道这种差异的根本原因

The source code as follows:

using namespace std;

int main()
{
        int m = 4;
        int arr[m] = {1, 2, 3, 4};
        printf("%d\n", arr[2]);
        return 0;
}

When I compile with g++, it compiles successfully as an executable. But when I compile with clang++, I get the following error:

VLAs.cpp:8:10: error: variable-sized object may not be initialized
        int arr[m] = {1, 2, 3, 4};
                ^
1 error generated.

After testing, I found that clang ++ can support the definition of VLBs(int arr[m];), but does not support defining VLBs while initializing them. I would like to know the root cause of this difference

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

轻许诺言 2025-02-14 21:18:06

VLA不是C ++,编译器以不同的方式支持它们。在C初始化VLA中,不支持VLA,这似乎也是Clang在C ++中所做的。另一方面,海湾合作委员会稍微扩大了对VLA的支持。您的下一个编译器可能根本没有VLA。

那么,如果C ++对此具有较高的机制,为什么要打扰:

#include <vector>
#include <array>

constexpr int n = 4;
std::array arr{1, 2, 3, 4};
std::array<int, n> arr2 = {1, 2, 3, 4};
std::vector<int> arr3 = {1, 2, 3, 4};

VLAs are not C++ and compiler support them differently. In C initializing VLAs is not supported and that seems to be what clang does in c++ as well. gcc on the other hand has extended the support for VLAs a bit. Your next compiler might not have VLAs at all.

So why bother if C++ has far superior mechanisms for this:

#include <vector>
#include <array>

constexpr int n = 4;
std::array arr{1, 2, 3, 4};
std::array<int, n> arr2 = {1, 2, 3, 4};
std::vector<int> arr3 = {1, 2, 3, 4};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文