{"id":4516,"date":"2020-12-26T00:01:56","date_gmt":"2020-12-26T08:01:56","guid":{"rendered":"https:\/\/c-for-dummies.com\/blog\/?p=4516"},"modified":"2021-01-02T08:26:15","modified_gmt":"2021-01-02T16:26:15","slug":"in-search-of-the-foreach-keyword","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=4516","title":{"rendered":"In Search of the <em>foreach<\/em> Keyword"},"content":{"rendered":"<p>C has three looping keywords: <em>do<\/em>, <em>for<\/em>, and <em>while<\/em>. These keywords construct a block of statements that repeat, hopefully but not necessarily with a terminating condition. Other programming languages offer additional looping keywords, including the popular and useful <em>foreach<\/em>.<br \/>\n<!--more--><br \/>\nForgetting about the <em>goto<\/em> keyword, the <em>foreach<\/em> keyword finds itself in languages that offer a richer variety of data constructions than C. In these languages, something I call a <em>collection<\/em> exists. This data structure is where you often see <em>foreach<\/em> used, though it can also be used with any array of data.<\/p>\n<p>Consider the following data set:<\/p>\n<p><code>$list = { \"Dr. No\", \"From Russia with Love\", \"Goldfinger\", \"Thunderball\" }<\/code><\/p>\n<p>One way a <em>foreach<\/em> keyword can be used on this collection is:<\/p>\n<p><code>foreach( $item in $list )<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;print $item<\/code><\/p>\n<p>The above code (assume it&#8217;s valid) outputs each string in the <code>$list<\/code> collection, represented as variable <code>$item<\/code> in the loop. A C language equivalent might be:<\/p>\n<p><code>for( i=0; i&lt;items; i++ )<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;printf(\"%d\\n\",list[i]);<\/code><\/p>\n<p>Unlike other types of loop, the <em>foreach<\/em> statement lacks an iteration counter. Instead, its job is to process the collection (the second argument) individually, using the first argument to repeatedly represent the items in the list.<\/p>\n<p>A <em>foreach<\/em> statement in C would operate on an array. Its loop count is the number of elements in an array. The C language lacks an operator (or method) to return an array&#8217;s size, so a specific calculation must be made to determine how many elements the array holds. This calculation is dependent upon the array&#8217;s data type.<\/p>\n<p>For example, in a character array, the number of elements is determined by dividing the memory size of the array by the size of the data type (<em>char<\/em>). This process is done differently for each array data type: <em>char<\/em>, <em>int<\/em>, <em>float<\/em>, pointers, and so on. The following code demonstrates:<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2020_12_26-Lesson-a.c\" rel=\"noopener\" target=\"_blank\">2020_12_26-Lesson-a.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n\r\nint main()\r\n{\r\n    char c[] = { 'a', 'b', 'c', 'd' };\r\n    int i[] = { 10, 100 };\r\n    float f[] = { 1.4, 5.7, 9.0, 22.7, 88.8 };\r\n    char *s[3] = { \"this\", \"that\", \"the other\" };\r\n\r\n    puts(\"Array element count:\");\r\n    printf(\"c = %lu\\n\",sizeof(c)\/sizeof(char) );\r\n    printf(\"i = %lu\\n\",sizeof(i)\/sizeof(int) );\r\n    printf(\"f = %lu\\n\",sizeof(f)\/sizeof(float) );\r\n    printf(\"s = %lu\\n\",sizeof(s)\/sizeof(char*) );\r\n\r\n    return(0);\r\n}<\/pre>\n<p>In the source code, the expression <code>sizeof(n)\/sizeof(type)<\/code> returns the number of elements in the array: <code>n<\/code> is an array variable and <code>type<\/code> is the variable&#8217;s data type. For the character pointer array, the data type is a <em>char<\/em> pointer, as shown in Line 14 with <code>sizeof(char*)<\/code>.<\/p>\n<p>Here&#8217;s the program&#8217;s output:<\/p>\n<p><code>Array element count:<br \/>\nc = 4<br \/>\ni = 2<br \/>\nf = 5<br \/>\ns = 3<\/code><\/p>\n<p>It&#8217;s possible to calculate the number of elements in the array, but what&#8217;s not obvious to the code is the array&#8217;s data type; the <em>sizeof<\/em> operator returns the proper sizes, but it can&#8217;t guess at the type of data it&#8217;s examining. This difficulty must be overcome if a <em>foreach<\/em> keyword is to be emulated in C.<\/p>\n<p>One trick is to use the size of an element in the array instead of the data type. For example, in an <em>int<\/em> array, element <code>a[0]<\/code> is the size of an integer. Likewise, in a <em>char<\/em> array, <code>a[0]<\/code> is the size of a <em>char<\/em>. Using this trick is demonstrated here:<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2020_12_26-Lesson-b.c\" rel=\"noopener\" target=\"_blank\">2020_12_26-Lesson-b.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n\r\nint main()\r\n{\r\n    char c[] = { 'a', 'b', 'c', 'd' };\r\n    int i[] = { 10, 100 };\r\n    float f[] = { 1.4, 5.7, 9.0, 22.7, 88.8 };\r\n    char *s[3] = { \"this\", \"that\", \"the other\" };\r\n\r\n    puts(\"Array element count:\");\r\n    printf(\"c = %lu\\n\",sizeof(c)\/sizeof(c[0]) );\r\n    printf(\"i = %lu\\n\",sizeof(i)\/sizeof(i[0]) );\r\n    printf(\"f = %lu\\n\",sizeof(f)\/sizeof(f[0]) );\r\n    printf(\"s = %lu\\n\",sizeof(s)\/sizeof(s[0]) );\r\n\r\n    return(0);\r\n}<\/pre>\n<p>This solution represents the first step to emulating the <em>foreach<\/em> keyword, as the array size is obtained. I continue to explore this concept in <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=4521\">next week&#8217;s Lesson<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The <em>foreach<\/em> looping keyword is found in many of the newer, trendier programming languages. Why not emulate it for C? <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=4516\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-4516","post","type-post","status-publish","format-standard","hentry","category-main"],"_links":{"self":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4516","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=4516"}],"version-history":[{"count":11,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4516\/revisions"}],"predecessor-version":[{"id":4558,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4516\/revisions\/4558"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=4516"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=4516"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=4516"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}