{"id":4521,"date":"2021-01-02T00:01:08","date_gmt":"2021-01-02T08:01:08","guid":{"rendered":"https:\/\/c-for-dummies.com\/blog\/?p=4521"},"modified":"2021-01-02T08:27:49","modified_gmt":"2021-01-02T16:27:49","slug":"emulating-the-foreach-keyword","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=4521","title":{"rendered":"Emulating the <em>foreach<\/em> Keyword"},"content":{"rendered":"<p>In <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=4516\">last week&#8217;s Lesson<\/a>, I covered how to obtain the number of elements in an array. This process is the first step to emulating the <em>foreach<\/em> keyword in the C language.<br \/>\n<!--more--><br \/>\nThe best approach is to divide the array size in memory by the size of its first element, which presents a consistent way to obtain the element count. Otherwise, a separate <em>foreach()<\/em> function must be crafted for each data type.<\/p>\n<p>Here is the expression: <code>sizeof(a)\/sizeof(a[0])<\/code>, where <code>a<\/code> is an array of any data type.<\/p>\n<p>To prove that this approach works, I created the following code. It identifies the size of array <code>f[]<\/code> and spews out the elements based on the <code>size<\/code> value calculated:<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2021_01_02-Lesson-a.c\" rel=\"noopener\" target=\"_blank\">2021_01_02-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    float f[] = { 1.4, 5.7, 9.0, 22.7, 88.8 };\r\n    int size,x;\r\n\r\n    size = sizeof(f)\/sizeof(f[0]);\r\n    for( x=0; x&lt;size; x++ )\r\n        printf(\"%.1f\\n\",f[x]);\r\n\r\n    return(0);\r\n}<\/pre>\n<p>The <em>foreach<\/em> part of the code is handled by the <em>for<\/em> loop at Line 9. Here is the output:<\/p>\n<p><code>1.4<br \/>\n5.7<br \/>\n9.0<br \/>\n22.7<br \/>\n88.8<\/code><\/p>\n<p>At this point, the goal is to create the <em>foreach<\/em> equivalent. Unfortunately, it can&#8217;t be a function. That&#8217;s because passing an array to a function passes the array&#8217;s address, not the full array. So any <em>sizeof<\/em> statement used within the function returns the size of the array&#8217;s address (a pointer, usually 8 bytes), not the size of the array in memory.<\/p>\n<p>No, to properly emulate a <em>foreach()<\/em> keyword in C, you must create a macro. It combines both Lines 8 and 9 from the preceding example:<\/p>\n<p><code>#define foreach(a,b) for(int a=0;a&lt;(sizeof(b)\/sizeof(b[0]));a++)<\/code><\/p>\n<p>Variable <code>a<\/code> is declared as an <em>int<\/em> within the macro. The rest of the assignment is a <em>for<\/em> loop, with the array size calculation as its middle part. Variable <code>b<\/code> represents the array.<\/p>\n<p>Obviously, this construction isn&#8217;t identical to a true <em>foreach<\/em> statement, nor does it match any of the alternatives I&#8217;ve seen presented on various programming websites. Despite my best efforts, it works within its given parameters: The second argument must be an array and the first argument is an integer variable not otherwise used in the function:<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2021_01_02-Lesson-b.c\" rel=\"noopener\" target=\"_blank\">2021_01_02-Lesson-b.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n\r\n#define foreach(a,b) for(int a=0;a&lt;(sizeof(b)\/sizeof(b[0]));a++)\r\n\r\nint main()\r\n{\r\n    float f[] = { 1.4, 5.7, 9.0, 22.7, 88.8 };\r\n\r\n    foreach(x,f)\r\n        printf(\"%.1f\\n\",f[x]);\r\n\r\n    return(0);\r\n}<\/pre>\n<p>The output is identical to the first example.<\/p>\n<p>This approach also works for creating simple repeating loops. For example:<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2021_01_02-Lesson-c.c\" rel=\"noopener\" target=\"_blank\">2021_01_02-Lesson-c.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n\r\n#define foreach(a,b) for(int a=0;a&lt;(sizeof(b)\/sizeof(b[0]));a++)\r\n\r\nint main()\r\n{\r\n    char c[] = \"abcdefg\";\r\n\r\n    foreach(x,c)\r\n        puts(\"Whee!\");\r\n\r\n    return(0);\r\n}<\/pre>\n<p>You need not do anything with the variable; just let the loop repeat, as shown in this output:<\/p>\n<p><code>Whee!<br \/>\nWhee!<br \/>\nWhee!<br \/>\nWhee!<br \/>\nWhee!<br \/>\nWhee!<br \/>\nWhee!<br \/>\nWhee!<\/code><\/p>\n<p>I would hope that a future update to C &mdash; a significant update &mdash; might include such new keywords as <em>foreach<\/em> and perhaps conveniences from other languages. Still, venerable C has survived without these additions. Obviously, anything you can think of can be programmed one way or the other. All you need is motivation and time.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The best way to create a <em>foreach<\/em> keyword or function is to write a macro. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=4521\">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-4521","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\/4521","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=4521"}],"version-history":[{"count":4,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4521\/revisions"}],"predecessor-version":[{"id":4559,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4521\/revisions\/4559"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=4521"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=4521"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=4521"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}