0

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

Evg
  • 25,259
  • 5
  • 41
  • 83
YoLo22
  • 1
  • If you're going to initialize `arr` at the point where you declare it, why don't let the compiler deduce its size? `int arr[] = {1,2,3,4};` – paolo Jun 16 '22 at 07:04
  • 6
    VLAs are a compiler extension and not part of the language. I assume that gives the compiler writers full freedom in how and what they want to support in regards to it. I doubt there is any meaningful answer here. – super Jun 16 '22 at 07:06
  • 2
    VLAs in standard C can't be initialized and I assume clang++ just took that as-is when adding this extension to C++ – Ted Lyngmo Jun 16 '22 at 07:07
  • 2
    Side question: What are VLBs? What does the B stand for? – Ted Lyngmo Jun 16 '22 at 07:09
  • 2
    The fact that you have both `using namespace std;` and `printf`, and you're using variable length arrays makes me really question whether you realize that C++ is not a perfect superset of C. – Chris Jun 16 '22 at 07:27
  • 2
    The real question is why get hung op on some non-standard extension of C++. VLA != C++. For run-time sized arrays there is std::vector – Pepijn Kramer Jun 16 '22 at 08:26
  • 1
    @TedLyngmo • VESA Local Bus (VLB). – Eljay Jun 16 '22 at 11:21
  • 1
    @Eljay Now, that's something I haven't heard about in many years :-) – Ted Lyngmo Jun 16 '22 at 11:22

1 Answers1

0

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};
Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42