Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is 1[&array] a proper replacement for &array[sizeof(array)/sizeof(array[0])] or way too obfuscated?

Tags:

arrays

c

C has no elementsof keyword to get the element count of an array. So this is commonly replaced by calculateing sizeof(Array)/sizeof(Array[0]) but this needs repeating the array variable name. 1[&Array] is the pointer to the first element right after the array, so you could use:

int myArray[12] = {1,2,3};  
int *pElement;

for (pElement = myArray; pElement < 1[&myArray]; pElement++)
{
  ...
}

to replace:

for (pElement = myArray; pElement < &myArray[sizeof(myArray)/sizeof(myArray[0])]; pElement++)
{
  ...
}

do you think this is too obfuscated?

like image 626
notan Avatar asked Feb 16 '18 08:02

notan


People also ask

Was the IS-1 A good tank?

The IS-1, like the KV-85 before it, was a great assist to the Soviet tank forces, giving them a heavily armoured tank with a great 85 mm gun that could defeat most of the German tanks in service except their heaviest ones such as the Tiger I and the Panther tanks.

IS-1 heavy tank?

The IS-1 heavy tank were essentially upgraded KV-1 Heavy Tank models. The IS-1 was born out of a Soviet Army need for more formidable tracked weapon systems to combat the ever-growing power of German tanks - particularly the newer Panther and Tiger I series appearing by the end of 1942.

Was the IS-6 ever made?

The IS-6 is a high-power breakthrough tank which was created during 1943-1944 to fight new German heavy tanks and self-propelled guns.


1 Answers

1[&myArray] is non-obvious. I suggest that you use temporary variables:

size_t count = sizeof array / sizeof *array;
int * const end = &array[count];
for (pElement = myArray; pElement < end; pElement++)

Or rather just use standard index variable:

size_t count = sizeof array / sizeof *array;
for(size_t i=0; i<count; ++i) {
    int *pElement = &array[i];

What ever you do, use temporary variables, because you can name them descriptively. It will make reading the code much faster, without affecting runtime performance (unless compiler is braindead).

like image 115
user694733 Avatar answered Nov 11 '22 21:11

user694733