diff --git a/doc/userdoc.org b/doc/userdoc.org index 95a577c9ba9284ef92356bcb6fc83edc88118367..092dcc3d66759cf7959f04f4e3844edcf80f9ba2 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