From d450c057e45ed3937989e43894206e99ef4be7dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Del=20Pino?= <stephane.delpino44@gmail.com> Date: Mon, 30 May 2022 14:23:56 +0200 Subject: [PATCH] Describe for loops --- doc/userdoc.org | 60 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/doc/userdoc.org b/doc/userdoc.org index 95a577c9b..092dcc3d6 100644 --- a/doc/userdoc.org +++ b/doc/userdoc.org @@ -1878,7 +1878,65 @@ We give a final illustration #+END_SRC #+results: if-block -*** TODO for loops +*** ~for~ loops + +~pugs~ allow to write ~for~ loops. It follows the ~C++~ syntax +#+BEGIN_SRC pugs :exports code + for (declarationinstruction ; condition ; postinstruction) statement +#+END_SRC +Following ~C++~, ~declarationinstruction~, ~condition~ and ~postinstruction~ +are optional. The ~condition~ argument if present *must* be a boolean +value (type ~B~), if it is absent, the default value ~true~ is used. + +- The ~declarationinstruction~ is execute only *once* /before/ the beginning + of the loop. The lifetime of the variable declared here is defined + by the ~for~ instruction itself. + +- The ~condition~ is evaluate /before/ each loop. + +- The ~postinstruction~ is executed /after/ each loop. + +- The ~statement~ is either a single instruction or a block of + instructions. The ~statement~ is executed if the ~condition~ has the + value ~true~. + +For instance, one can write +#+NAME: for-block +#+BEGIN_SRC pugs :exports both :results output + let n:N, n = 10; + let sum:N, sum = 0; + for (let i:N, i=1; i<=n; ++i) { + sum += i; + } + cout << "sum = " << sum << "\n"; +#+END_SRC +which gives as expected +#+results: for-block + +The lifetime of the declared variable (in the ~declarationinstruction~ +statement) is illustrate by the following example +#+NAME: for-scope-error +#+BEGIN_SRC pugs-error :exports both :results output + for (let i:N, i=0; i<2; ++i) { + cout << "i = " << i << "\n"; + } + cout << "i = " << i << "\n"; +#+END_SRC +Running this example produces the following error +#+results: for-scope-error + +To fix the previous code, one can write +#+NAME: for-no-decl +#+BEGIN_SRC pugs :exports both :results output + let i:N, i=0; + for (; i<2; ++i) { + cout << "i = " << i << "\n"; + } + cout << "i = " << i << "\n"; +#+END_SRC +One gets +#+results: for-no-decl + *** TODO do while loops -- GitLab