[comp.lang.c] Scoping question

keith@Stardent.COM (Keith Crews @stardent) (03/06/90)

int ia[5];
main() {
	int i = 1;
	{
	    int *ip = &ia[i];
	    int i = 0;
	    printf("ip = 0x%x, &ia[i] = 0x%x, &ia[1] = 0x%x, i = %d\n",
		ip, &ia[i], &ia[1], i);

	}
	{
	    int i = 0;
	    int *ip = &ia[i];
	    printf("ip = 0x%x, &ia[i] = 0x%x, &ia[1] = 0x%x, i = %d\n",
		ip, &ia[i], &ia[1], i);
	}
}

In the 2 blocks above which i should be used in calculating the value
of ip?  Should it be the inner i in both cases or the outer i in the
first and the local i in the second?  Is the answer the same for pcc
and ansi?

K&R section 11.1 reads "... if an identifier is explicitly declared at the 
head of a block, ..., any declaration of that identifier outside the block 
is suspended until the end of the block." This really does not 
address what i is visible between the start of the block and the 
declaration of the local i. I suspect that most compilers do what Sun's 
does and use the outer i in the first case and the inner in the second case 
but not all others do. 

This example is simplified from some code in gcc which is like:

	for (i = 0; i < X; i++) {
	    for (j = 0; j < Y; j++) {
		MACRO(a[i], b[j]);
	    }
	}

The intent is clear but MACRO defines its own i and at least one
compiler uses that i when calculating a[i].
-- 
Keith Crews			Stardent Computer Inc.
				95 Wells Avenue, Newton, MA 02159