Recently I saw an answer on a question where they explained that addressing arrays in this way <number>[array]
is valid C code.
How do square brackets work in C?
Example:
char x[] = {'A','B','C','D','E','F','G','H','I','J'};
printf("%d\n",5[X]);
//Will print 70 == 'F'
This kind of notation seems cumbersome and potentially confusing for everybody including the author.
Does this way of addressing arrays come with some justifiable advantage?
or
Can I continue with my life without worrying?
: The elements field within square brackets [], representing the number of elementsin the array, must be a constant expression, since arrays are blocks of static memory whose size must be known at compile time.
We need to give the size of the array because the complier needs to allocate space in the memory which is not possible without knowing the size. Compiler determines the size required for an array with the help of the number of elements of an array and the size of the data type present in the array.
There are three different kinds of arrays: indexed arrays, multidimensional arrays, and associative arrays.
Arrays are used when there is a need to use many variables of the same type. It can be defined as a sequence of objects which are of the same data type. It is used to store a collection of data, and it is more useful to think of an array as a collection of variables of the same type.
I have never encountered this in "real code" (i.e., outside of intentionally obfuscated things and puzzles with artificial limitations) so it would seem that it is quite universally agreed that this shouldn't be done.
However, I can come up with a contrived example where it might be considered by some (not necessarily me) a nicer syntax: if you have multiple pieces of data related to a single entity in a column, and you represent the rows as different arrays:
enum { ADA, BRIAN, CLAIRE };
const char *name[] = { "Ada", "Brian", "Claire" };
const unsigned age[] = { 30, 77, 41 };
printf("%s is %u years old\n", ADA[name], ADA[age]);
I will be the first to agree that this obfuscates the syntax by making it look like the people are the arrays instead of being the indexes, and I would prefer an array of struct
in most cases. I think a case could be made for this being nicer-looking, though, or perhaps in some cases it would be a way to swap the rows and columns (arrays and indexes) with minimal edits elsewhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With