Skip to main content

Command Palette

Search for a command to run...

Standard c++

Published
2 min readView as Markdown

Why int arr[n]; Works on Some Compilers but Is Still Wrong in Standard C++

Introduction

Many C++ learners face a confusing situation:
They read that this code is not allowed in C++—

int n;
cin >> n;
int arr[n];

—but when they run it, it works perfectly.

This raises a natural question:

If it works, why do people say it is wrong?

The answer lies in understanding C++ standards, compiler extensions, and stack memory behavior.
This article explains the topic clearly, deeply, and professionally, separating what works from what is correct.


The Key Rule in Standard C++

According to the C++ language standard:

The size of an array allocated on the stack must be known at compile time.

This means only constant expressions are allowed:

int arr[5];     // ✅ valid

But not:

int n;
cin >> n;
int arr[n];     // ❌ invalid in standard C++

Here, n is known only at runtime, so the compiler cannot determine stack memory requirements during compilation.


Then Why Does the Code Still Work?

The Real Reason: Compiler Extensions

Some compilers—most notably GCC—support a feature called:

🔹 Variable Length Arrays (VLAs)

  • VLAs originate from C99 (the C language)

  • GCC extends this feature into C++

  • This is not part of the C++ standard

So when your code works, it is not because it is valid C++—
it works because your compiler is being permissive.

📌 Important distinction:

Working code ≠ Standard-compliant code


What the Compiler Actually Does

When GCC encounters:

int arr[n];

It:

  • Generates runtime stack allocation instructions

  • Dynamically adjusts the stack pointer

  • Allows stack size to change at runtime

This behavior:

  • Is compiler-specific

  • Is non-portable

  • Is undefined by the C++ standard

Other compilers (like MSVC) reject this code entirely.


Why Stack VLAs Are Dangerous

1. Limited Stack Memory

Stack memory is small and fixed.

int n = 10'000'000;
int arr[n];   // 💥 likely stack overflow

Heap memory does not have this limitation.


2. Non-Portable Code

Code that:

  • Works on GCC

  • Fails on MSVC

  • Behaves differently on Clang

is not professional C++ code.

More from this blog

Amit singh's blog

235 posts