In the program I have pasted below, I was just wondering why the pointer “p” was initialized within the for loop? I am used to reading the conditions of a for loop as: starting from this value of a variable; until it reaches this value; increment it by this much. So it seems strange to have another variable that does not determine the ending condition and is not being incremented during each iteration in there at all.
I would have just put p=&a[0]; above the for loop and left the rest. Is this just a stylistic thing or are there differences in the way things are processed depending on where you initialize p? Is one way preferred over the other?
#include <stdio.h>
#define PRD(a) printf("%d", (a) )
int a[]={0, 1, 2, 3, 4};
int main()
{
int i;
int* p;
for (p=&a[0], i=0; i<=4; i++) PRD(p[i]);
return 0;
}
This appears to be just a style thing. I would probably have also put the initialisation of
poutside theforstatement, since cramming everything in there makes the code harder to read. (Because the pattern of thatforloop is different from what you might usually expect, an experienced programmer will have to stop, back up, and think about what’s in there before it will make sense. I initially thought there were four clauses in theforcontrol statements until I noticed that the first separator was a comma.)Writing the code like this (instead of initialising
poutside the loop) will have no effect on performance.