0

In the book 21st Century C Tips From the New School. On page 171 it says,

Now for the sad part: let us say that you have a variable-length array (i.e., one whose length is set by a runtime variable). The only way to zero it out is via memset :

int main(){
  int length=20;
  int ll[length];
  memset(ll, 0, 20*sizeof(int));
}

So it goes. 1.

The footnote for that section reads,

  1. You can blame ISO C standard §6.7.8(3) for this, because it insists that variable length arrays can’t be initialized. I say the compiler should be able to work it out.

I don't see this mentioned anywhere though in the seminal answers on this matter on StackOverflow which seem to suggest that this would work,

int main(){
  int length=20;
  int ll[length] = {0};
}

Is this the proper reading of the ISO C 2011 Standard?

Community
  • 1
  • 1
Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
  • 5
    `I don't see this mentioned anywhere though in the seminal answers on this matter on StackOverflow` Probably because the linked question doesn't mention variable length arrays at all. – tkausl Jun 26 '18 at 07:46
  • 1
    You cannot initialize VLA's, instead use `memset` or a loop. – David C. Rankin Jun 26 '18 at 07:47
  • 1
    Or better don't use VLA... => I'm already gone – Stargateur Jun 26 '18 at 07:48
  • ... (or calloc) – Attersson Jun 26 '18 at 07:48
  • 8
    What amazes me is the hardocded `20*sizeof(int)`, instead of `sizeof ll`. I mean, if the book professes to teach C, it shouldn't have brittle code in it. – StoryTeller - Unslander Monica Jun 26 '18 at 07:52
  • Worse yet is the use of identifiers such as `ll` or `l`. This is a _very_ old and well-known no-no discovered somewhere in the 1970s-1980s. I'd expect a moderately experienced C programmer to be aware of it - let alone someone bold enough to write a C book. 21st century, right... – Lundin Jun 26 '18 at 14:53
  • @StoryTeller Well, `sizeof ll` is potentially less efficient than `20*sizeof(int)`. Because: VLA. – Lundin Jun 26 '18 at 14:55
  • @Lundin link or docs that explain your statement? – Evan Carroll Jun 26 '18 at 17:47
  • @EvanCarroll: I would expect that if `ll` is a VLA, using `sizeof` on it would result in a compiler computing its size at run time. A compiler might recognize some cases where the length would always be the same, but I'm not sure the value of such optimizations would be worth the effort. – supercat Jun 26 '18 at 20:31
  • @EvanCarroll It's because of the familiarity in the font between `1` (one) and `l` (L). Using `l` as variable name is banned by MISRA-C, [CERT-C](https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152241) etc. – Lundin Jun 27 '18 at 07:00

0 Answers0