How do compilers treat variable length arrays

前端 未结 4 1771
自闭症患者
自闭症患者 2020-11-30 13:59

This might seem like a beginner\'s question, but I am interested in the way that a compiler normally creates arrays of variable-dimensions, like in the following program.

4条回答
  •  死守一世寂寞
    2020-11-30 14:48

    In the C99 version of the C standard, variable length arrays are permitted. However, they are not permitted in any version of C++; you're seeing a G++ extension. Note that Microsoft's C compiler does not fully support C99; since G++ supports C99 it's easy enough to apply the VLA support to C++ as an extension.

    As to how the compiler usually implements VLAs, it's the same as alloca() (except that it has to keep the size around for sizeof) - the compiler saves the original stack pointer, then adjusts it down by however many bytes it calculates that it needs. The downside is function entry and exit is a bit more complicated as the compiler needs to store where to reset the stack pointer to rather than just adjusting by fixed constants.

提交回复
热议问题