0

Reference to the Stackoverflow question title "variable length arrays in C++" we know that following is valid

void foo(int n) {
    int values[n]; //Declare a variable length array
}

I have read that there exists a small run time penalty(in variable length arrays) here. Can somebody nicely explain what that is in this context?

I would also try my level best to locate the link where I read it.I apologize i could not mention it here.

Community
  • 1
  • 1
Naseer
  • 4,041
  • 9
  • 36
  • 72
  • 4
    It would be nice if you actually had a *link* to the question you reference. Also, variable-length arrays didn't technically exist in C++ until the C++14 standard, though many compilers had it as an extension. – Some programmer dude Nov 12 '14 at 08:36
  • Most things have a cost associated with them. VLAs are no exception. When you say there's a penalty, you mean as compared to what? – NPE Nov 12 '14 at 08:38
  • As compared to normal way of when we use arrays like int values[10]; – Naseer Nov 12 '14 at 08:40
  • 2
    @JoachimPileborg: Apparently VLA's didn't make it into C++14 after all: https://en.wikipedia.org/w/index.php?title=C%2B%2B14&diff=591269892&oldid=589637208 – janneb Nov 12 '14 at 09:02
  • Follow standard, use `vector` instead. – Ajay Nov 12 '14 at 09:11
  • @janneb Oh, missed that! Doesn't seem to be included (yet) for C++17 either. Anyway, using `std::vector` should give all benefits of VLAs without the drawbacks (though it adds other drawbacks). – Some programmer dude Nov 12 '14 at 09:12

1 Answers1

3

IIRC, with GCC, functions with VLA's:

  • Will not be inlined
  • Need to use an extra register for the frame pointer (that is, -fomit-frame-pointer works on non-VLA functions), so there is one less register available for the other work the function needs to do.
Ajay
  • 18,086
  • 12
  • 59
  • 105
janneb
  • 36,249
  • 2
  • 81
  • 97
  • 2
    Also, if the VLA is placed before other variables in the stack frame, one can no longer use constant offsets to access them. – Blagovest Buyukliev Nov 12 '14 at 08:41
  • 1
    @BlagovestBuyukliev: Good point. Though I think by using either the stack or frame pointer, constant offsets can be used (hence why -fomit-frame-pointer is disabled for VLA functions). But if there are variables placed between two VLA's then I see no other way than to compute the offset at runtime. – janneb Nov 12 '14 at 08:49
  • Even if VLAs are put "last", there's the case of multiple VLAs... then the address of all-but-the-first will depend on the cummulative size of the earlier ones. And you can't actually put the non-VLA ones first without taking a worst-case high watermark of all memory needed for variables in internal `{}` scopes (e.g. `for`, `while`) in a function, so the performance impact's unlikely to be restricted to VLA access. – Tony Delroy Nov 12 '14 at 09:22