You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: blogPosts/macroTutorial.nim
+44-7Lines changed: 44 additions & 7 deletions
Original file line number
Diff line number
Diff line change
@@ -138,22 +138,58 @@ do{
138
138
i += 1;
139
139
}while(i < 10);
140
140
```
141
+
142
+
We present below two templates that attempt to replicate this construct in Nim. The first one is not guaranteed to work if the loop contains some `break` or `continue` keyword.
The following code only works with the second template version.
170
+
"""
171
+
nbCodeSkip:
172
+
for msg in ["Hello even world", "Goodbye even world"]:
173
+
var i =1
174
+
doWhile i <10:
175
+
if i mod2!=0:
176
+
inc i
177
+
continue
178
+
echo i, ": ", msg
179
+
i +=2
180
+
181
+
nbText:"""
182
+
With this code we attempt to print messages with only even numbers. The `if` block ensures
183
+
that we do not enter the main part of the `while` loop body
184
+
without an even value in the variable `i`.
185
+
With `continue`, we go back to the beginning of the loop to ensure that our variable is not greater than 10. With the first template version, the `loop` is first executed outside of the `while` loop and `continue` skip to the next iteration of the `for` loop instead, effectively skipping all `echo` statements.
186
+
187
+
With the keyword `defer` all the statements are kept inside the `while` loop.
188
+
"""
189
+
154
190
155
191
nbText:hlMd"""
156
-
Notice though that _syntaxically_ the resulting source code is fairly different than the C++ code.
192
+
Notice also that _syntaxically_ the resulting source code is fairly different than the C/C++ code.
157
193
158
194
In the C source code, appear in this order:
159
195
1. the `do` keyword
@@ -698,7 +734,8 @@ There are plentiful of posts in the forum that are good references:
0 commit comments