Foreach loop: Difference between revisions

Content deleted Content added
Square brackets pair. WP:CATEGORYs add.
Line 120:
 
Most general: string or array as collection (collection size known at run-time)
: ''Note: {{code|idxtype}} can be removed and <code>[[typeof]](col[0])</code> used in its place with [[GNU Compiler Collection|GCC]]''
<syntaxhighlight lang="c" highlight="5-8" line>
#include <stdio.h>
Line 200:
The compiler uses [[argument-dependent lookup]] to resolve the <code>begin</code> and <code>end</code> functions.<ref>{{cite web|url=https://en.cppreference.com/w/cpp/language/range-for |title=Range-based for loop (since C++11) |publisher=en.cppreference.com |access-date=2018-12-03}}</ref>
 
The [[C++ Standard Library]] also supports <code>for_each</code>,<ref>{{cite web|url=http://en.cppreference.com/w/cpp/algorithm/for_each |title=std::for_each - cppreference |publisher=en.cppreference.com |access-date=2017-09-30}}</ref> that applies each element to a function, which can be any predefined function or a lambda expression. While range-based for is only from the beginningstart to the end, the range andor direction you can changebe the direction or rangechanged by altering the first two parameters.
 
<syntaxhighlight lang="Cpp">
Line 410:
[[Go (programming language)|Go]]'s foreach loop can be used to loop over an array, slice, string, map, or channel.
 
Using the two-value form, we getgets the index/key (first element) and the value (second element):
<syntaxhighlight lang="go">
for index, value := range someCollection {
Line 417:
</syntaxhighlight>
 
Using the one-value form, we getgets the index/key (first element):
<syntaxhighlight lang="go">
for index := range someCollection {
Line 656:
NSArray *a = [NSArray new]; // Any container class can be substituted
 
for(id obj in a) { // Note the dynamicDynamic typing (weis doused. notThe needtype toof knowobject thestored
// Type of object stored in 'a'. can Inbe fact,unknown. thereThe array can behold many different
// many different types of object in the array.
 
printf("%s\n", [[obj description] UTF8String]); // Must use UTF8String with %s
Line 821:
<syntaxhighlight lang="php">
$arr = array(1, 2, 3);
foreach ($arr as &$value) { // Note theThe &, $value is a reference to the original value inside $arr
$value++;
}