From inside a loop, nested within another loop [etc], returning to the base code block.
Python |
Qt/Cpp |
- r = 10
- n = 240
- for x in range(r):
- for y in range(r):
- for z in range(r):
- # Start reading here
- if x * y * z == n:
- print(x,y,z)
- # 5 6 8
- break
- else:
- continue
- break
- else:
- continue
- break
|
- const int r(10 );
- const int n(240);
- for ( int x = 0; x < r; x++ ) {
- for ( int y = 0; y < r; y++ ) {
- for ( int z = 0; z < r; z++ ) {
- // Start reading here
- if ( x * y * z == n ) {
- qDebug() << x << y << z;
- goto finished;
- }
- }}} finished:
|
Read as:
|
- if [ expression is true ]
- print x y z
- 'break'out of loop z [ ignore the else ]
- 'break'out of loop y [ ignore the else ]
- 'break'out of loop x.
|
- if [ expression is true ]
- debug out x y z
- and goto finished [ label ]
|
Benefits:
|
- In python, you can place an "else" statement after a loop ( "for" or "while" ) which gets called if the loop exits without a 'break' statement. This is a novell construct absent in c++."
|
- This code, is clean, and in this particular case, no extra indentation was needed.
- the "goto" label is particularly descriptive: "[ I am finished ] goto finish line."
|
Drawbacks:
|
- This "else" feature is esoteric and unknown towards most Python developers.
- The "else" mistakenly seems like the continuation to the "if" statement above.
- This feature does not exist in any other language, making this a non-transferable idiom.
- Indentation structure is bumpy and disorienting.
|
|