Systems CourseC/C++ · Linux · Memory
C++ Language & SafetyLesson 17 of 441 min read7 questions

Compile-time Constants & VLAs

Why int arr[n] with a runtime n is not standard C++.

Test yourself ↓

Concept core idea Watch out easy to get wrong

Concept

Key concepts

  1. constexpr int s = 5*4; int a[s]; → legal, portable (compile-time constant).
  2. const int s = 5*4; int a[s]; → also legal in C++ (const + constant initializer).
  3. int s = 5*4; int a[s]; → NOT standard C++ — a VLA (Variable Length Array).
  4. VLAs are valid in C (C99); g++/clang allow them as a non-standard extension; MSVC rejects them.
  5. -pedantic surfaces the warning in EVERY C++ standard (98→20); the flag, not the version.

Prove it with the compiler

Bash
g++ -std=c++17 -pedantic t.cpp        # warning: ISO C++ forbids variable length array
g++ -std=c++17 -pedantic-errors t.cpp  # hard error
g++ -std=c++17 t.cpp                    # no warning (extensions on)
Watch out

Easily confused

const int size vs plain int size
const int (with a constant initializer) is a compile-time constant → valid array size. A plain int is a runtime variable → VLA (non-standard).
compiler allows vs standard allows
g++ accepting it (extensions on) is not the same as the C++ standard allowing it. -pedantic shows the difference.

Test yourself

7 questions on this lesson. Write your answers from memory, then compare them with the model answers side by side.