Search code examples
cloopsinitializer-listinitializing

C/C++ : Why is it impossible to declare a pointer in loop initialization


When printing an array, initializing an integer works.

int a[MAX_SIZE] = {1,2,3,4,5,6,7,8,9,10};

for (int i = 0; i <= (MAX_SIZE - 1); i++)
{
    printf("%3d",a[i]);
}

However, I wonder why initializing a pointer to an integer ("walker") won't work:

int a[MAX_SIZE] = {1,2,3,4,5,6,7,8,9,10};

for (int *aWalk = a, int *aEnd = a + MAX_SIZE - 1; aWalk <= aEnd; aWalk++)
{
    printf("%3d", *aWalk);
}

Solution

  • The statement int *aWalk = a, int *aEnd = a + MAX_SIZE - 1; wouldn't even work on its own, so it can't work in a loop header either. The syntax you are looking for is this:

    int *ptr1 = some_address, *ptr2 = some_other_address;
    

    This works inside and outside of a loop. Also, note that your problem is not declaring one pointer but two. That's also why you are supposed to first extract a minimal example.