Does C have a “foreach” loop construct?

前端 未结 12 2201
情书的邮戳
情书的邮戳 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:42

    C has 'for' and 'while' keywords. If a foreach statement in a language like C# looks like this ...

    foreach (Element element in collection)
    {
    }
    

    ... then the equivalent of this foreach statement in C might be be like:

    for (
        Element* element = GetFirstElement(&collection);
        element != 0;
        element = GetNextElement(&collection, element)
        )
    {
        //TODO: do something with this element instance ...
    }
    

提交回复
热议问题