0

I am trying to implement foreach with some c macros:

// implement foreach with c macro, tag_c
#include <stdio.h>
#include <stdlib.h>
// foreach implementation for char arrays
#define forchar(iter, array) char* iter; for(iter = array; (*iter) != '\0'; iter++)
// 'foreach' implementation for string arrays, make sure the array ends with NULL
#define forstr(iter, array) char** iter; for(iter = array; *iter; iter++)

int main(int argc, char const* argv[])
{
    char str[] = "what I think is this.";
    forchar(iter, str) {printf("%c ", *iter);}
    printf("\n");
    char *strarray[] = {"Hello, how are you?", "I am fine, thanks. And you?", "I am ok, thanks."};
    forstr(iter1, strarray) {
        printf("%s\n", *iter1);
    }
    return 0;
}

Note that strarray does not end with an NULL element, but the program runs fine:

gcc -o bin for2.c && ./bin
w h a t   I   t h i n k   i s   t h i s .
Hello, how are you?
I am fine, thanks. And you?
I am ok, thanks.
qed
  • 22,298
  • 21
  • 125
  • 196
  • 2
    You've lucked out. Walking off the end of an array is undefined behavior. This compiler, with these settings, with that array, at that stack position, seems to have padded things with some zero bytes after the array. Do *not* count on that working in the future. Add your own `NULL`. – Paul Roub Oct 18 '14 at 12:42
  • `char *strarray[4] = {...` – BLUEPIXY Oct 18 '14 at 12:43
  • Your `for...` macros are dangerous and completely useless. C has `for` scope variables since 1999. And hiding such control structures in a macro, for not much gain is frowned upon by large parts of the C community. – Jens Gustedt Oct 18 '14 at 13:00

0 Answers0