0

Why can't variable length arrays in C be declared as static? For example, this declaration is not allowed:

static char str1[lengthOfaString];
12
  • 1
    C99? What is the error? Paste lengthOfaString declaration please Commented Dec 28, 2016 at 16:24
  • 2
    Because you cannot determine the lenght of a string in a static context. Commented Dec 28, 2016 at 16:24
  • 6
    Because static storage duration means the object exists for the entire life of the program, including before any non-constant expression -- such as one used as an array length -- is evaluated. Thus, the length of a static array needs to be a compile-time constant. Commented Dec 28, 2016 at 16:25
  • @DavidIsla lengthOfaString is an int variable that holds a length of another string Commented Dec 28, 2016 at 16:26
  • 2
    @DavidIsla This does not change anything. It still is a variable. C is not C++! Commented Dec 28, 2016 at 19:27

1 Answer 1

6

When applied to a local identifier, the static keyword specifies that the object designated by that identifier has static storage duration. That means the object exists for the entire life of the program, from before the evaluation of any non-constant expression.

By definition, variable-length arrays have length designated by an expression that is evaluated at runtime, when control reaches the array declaration. The system cannot provide for such an object to have static storage duration because it does not know the object's size until some time after the object must already exist.

Note also that all file-scope variables have static storage duration, and therefore VLAs cannot be declared at file scope at all. Indeed, at file scope, the static keyword has nothing to do with storage duration; instead, in that context it specifies internal linkage.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.