Home >Backend Development >C++ >Why Do Variable-Length Arrays Work in This C Code Despite the Constant Array Bound Rule?

Why Do Variable-Length Arrays Work in This C Code Despite the Constant Array Bound Rule?

DDD
DDDOriginal
2024-12-16 11:40:10112browse

Why Do Variable-Length Arrays Work in This C   Code Despite the Constant Array Bound Rule?

Variable Length Arrays in C Despite Constant Array Bound Requirement

In C , it is stated that the array bound must be a constant expression. However, in certain code scenarios, it appears that this rule is violated without causing any errors. Consider the following example:

#include <iostream>
using namespace std;

int main(){
    int n=10;
    int a[n];

    for (int i=0; i<n; i++) {
        a[i]=i+1;
        cout<<a[i]<<endl;
}
    return 0;
}

As per textbooks, this code should raise an error since n is not a constant expression. Surprisingly, it executes flawlessly in Xcode4 under Mac. What explains this apparent contradiction?

The answer lies in a C99 feature called Variable Length Arrays (VLAs). Although primarily used in C, certain compilers support VLAs in C as well. In this context, int a[n] is a VLA that allocates space on the stack akin to int a[10].

Therefore, the code above uses a VLA with a variable length n. This feature permits the creation of arrays with dynamically determined sizes, even though the array bound is technically not a constant expression.

The above is the detailed content of Why Do Variable-Length Arrays Work in This C Code Despite the Constant Array Bound Rule?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn