You cannot do this in regular C. However, you can fake it with a macro:
#define FOR_EACH(type, x, array, size, code) \ do { \ int i; \ for (i=0; i<size; ++i) { \ type x = array[i]; \ code \ } \ } while(0) int main() { int arr[] = {0,1,2,3,4,5,6}; FOR_EACH(int, x, arr, 7, printf("%d ", 1 << x); ); return 0; }
EDIT
I coded the example to be more portable - without using the GCC block extension.
Agnius vasiliauskas
source share