Why Does This C++ Code Declaring an Array with User Input Work?

0
10
Asked By CreativeCoder27 On

I've got a question about this C++ code that I ran, which seems to allow me to declare an array using a variable that's only known at runtime. Here's the code snippet:

```cpp
#include

int main()
{
int n;
printf("Number of elements: "); scanf("%d", &n);

int a[n]; // Shouldn't this throw an error since n isn't known at compile time?

for(int i = 0; i < n; i++) a[i] = i;

for(int i = 0; i < n; i++) printf("element %3d: %dn", (i+1), a[i]);

return 0;
}
```

When I compile it with g++ and run it, the program correctly asks for the number of elements and works perfectly fine. How can this be? I thought C++ needed to know the array size at compile time.

3 Answers

Answered By StackGuru99 On

Actually, the way you’re using `int a[n];` creates a VLA, which was introduced in C99. It means the array `a` is allocated on the stack with a size determined at runtime. Just remember that it can lead to stack overflow if `n` is too large, so it’s a bit limited compared to using `std::vector`. C++ doesn’t officially support VLAs, but some compilers like GCC allow them as an extension.

CodeMaster88 -

How does that work with stack vs heap? I thought dynamic allocation was always on the heap.

Answered By CplusplusNinja On

Good question! Typically in C++, arrays need a fixed size at compile time. By writing `int a[n];`, you're using a VLA, which isn’t standard C++. It’s a GCC feature that allows for this kind of flexibility, but just be cautious as it might not compile on other compilers that strictly adhere to the standards.

DevDude22 -

So, I guess if I switch compilers and it doesn’t support VLAs, I might run into trouble, right?

Answered By ArrayWhisperer42 On

The behavior you're noticing comes from Variable Length Arrays (VLAs), which aren’t part of the standard C++ but are a GCC extension. It seems surprising that the compiler lets you declare an array with `int a[n];` when `n` isn’t known at compile time, but that’s because GCC bends the rules a bit. In standard C++, you should probably use something like `std::vector a(n);` instead — that’s the reliable and portable way to handle dynamic-sized arrays!

TechSavvyDude -

Does this feature exist in C as well? I thought VLAs were a C-specific thing but wasn’t sure!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.