-5

In my company, when I am looking in the code part, I was wondering when I see an array variable declaration similar to like this

int arr[0]; (Using c language)

Could anyone help me to state that what this declaration meant for? How this declaration can make use of realtime of codepart?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52

1 Answers1

2

It is an error insofar that it is neither standard C nor standard C++.

This is the old (i.e. pre-C99) way of inserting a variable length array as a struct member, which was never standard C although some compilers (e.g. GCC) support it as an extension. It has to be the last member of the struct.

Post C99, the now standard way to do this is to use empty brackets.

For C++ you're out of luck - variable length arrays are not standard C++. But you can use std::vector instead.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Could you expain with an example please.... – satish kumar Mar 30 '17 at 12:08
  • 1
    You already read the GCC documentation StoryTeller linked in a comment, right? That contains an example, so why are you asking for another one? – Useless Mar 30 '17 at 12:25
  • 1
    It is related to the 'struct hack', but the struct hack needed a dimension of 1 because 0 isn't valid in C. – Jonathan Leffler Mar 30 '17 at 12:55
  • Indeed. The "struct hack" used 1 and had poorly-defined behavior (because you'd write out of bounds of the array and there might also be padding) and the gcc zero-length array had well-defined behavior but was not standard. This gcc non-standard extension lead to the introduction of flexible array members in C99. Therefore both the "struct hack" and GCC zero-length arrays are bad and obsolete methods. – Lundin Mar 30 '17 at 14:57