Skip to content

Commit d5d3004

Browse files
committed
Add example showing equivalent of Cpp1 for( auto i=0; i < 10; ++i ) loop
Closes #1063
1 parent e12e301 commit d5d3004

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

Diff for: docs/cpp2/contracts.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ For example:
3232
``` cpp title="Precondition and postcondition examples" hl_lines="2 3"
3333
insert_at: (container, where: int, val: int)
3434
pre<bounds_safety>( 0 <= where <= container.ssize(), "position (where)$ is outside 'container'" )
35-
post ( container.ssize() == container.ssize()$ + 1 )
35+
post ( container.ssize() == container.ssize()$ + 1 )
3636
= {
3737
_ = container.insert( container.begin()+where, val );
3838
}

Diff for: docs/cpp2/functions.md

+16
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,22 @@ if i % 2 == 1 // if i is odd
266266
// counter: 1, word: [Betty]
267267
```
268268

269+
Here is the equivalent of the Cpp1 code `for ( int i = 0; i < 10; ++i ){ std::cout << i; }`:
270+
271+
``` cpp title="Equivalent of Cpp1 'for ( int i = 0; i < 10; ++i ){ std::cout << i; }'"
272+
(copy i := 0)
273+
while i < 10
274+
next i++ {
275+
std::cout << i;
276+
}
277+
```
278+
279+
Line by line:
280+
281+
- `(copy i := 0)`: Any statement can have [statement-local parameters](declarations.md#from-functions-to-local-scopes-and-back-again), and this is declaring `i` as an `int` that's local to the loop. Parameters by default are `const`, and for not-cheap-to-copy types they bind to the original value; so because we want to modify `i` we say `copy` to explicitly declare this is the loop's own mutable scratch variable.
282+
- `while i < 10`: The termination condition.
283+
- `next i++`: The end-of-loop-iteration statement. Note `++` is always postfix in Cpp2.
284+
269285

270286
### Loop names, `#!cpp break`, and `#!cpp continue`
271287

0 commit comments

Comments
 (0)