Weird arrays in C

Recently I've saw quite strange way to create an array in C. I will describe it bellow - looks quite interesting!

Let's assume we have an array given bellow:

int myArray[4];
We could rework it, so that each element is declared separately:
    int myArray0;
    int myArray1;
    int myArray2;
    int myArray3;

Now we can obtain pointer to first element and last element, and iterate through elements in between it as with regular array. We exploit that compiler will probably put those variables in the same order in the same place in memory.

A full example is given below:

#include <stdio.h>

void processElement(int e)
{
    printf("processing element in array, it has value %d\n", e);
}

int main()
{
    int myArray0 = 0;
    int myArray1 = 1;
    int myArray2 = 2;
    int myArray3 = 3;

    // dummy way to force compiler not to optimalize-out our array members
    printf("%d\n%d\n%d\n%d\n", &myArray0, &myArray1, &myArray2, &myArray3);

    int *start = &myArray0;
    int *stop = &myArray3;

    if(start > stop)
    {
        start = &myArray3;
        stop = &myArray0;
    }

    for(int* it= start; it <= stop; *it++)
    {
       processElement(*it);
    }
}

:)

0 commentaires:

Post a Comment