Does C have a “foreach” loop construct?

前端 未结 12 2204
情书的邮戳
情书的邮戳 2020-12-02 03:49

Almost all languages have a foreach loop or something similar. Does C have one? Can you post some example code?

12条回答
  •  醉梦人生
    2020-12-02 04:27

    While C does not have a for each construct, it has always had an idiomatic representation for one past the end of an array (&arr)[1]. This allows you to write a simple idiomatic for each loop as follows:

    int arr[] = {1,2,3,4,5};
    for(int *a = arr; a < (&arr)[1]; ++a)
        printf("%d\n", *a);
    

提交回复
热议问题