Hacker Timesnew | past | comments | ask | show | jobs | submitlogin

I use this convention often for loops:

    for (int x = 0; x < width; x++)
    for (int y = 0; y < width; y++)
    if ((x + y) % 3) {
      // ...
    }
The semantics are kind of like using a comprehension.


I abhor deep indents, and when I have deeply nested loops that just serve to trivially enumerate things, in C I sometimes add a helper function for the iteration.

e.g. instead of:

    for(int i=0;i<N;i++){
        for(int j=0;j<K;j++){
            for(int k=0;k<L;k++){
                  ...
it might become

    i=j=k=0;
    while(all_frob_indices(&i,&j,&k)){
        ....
with all_frob_indices() doing the i++; if(i>N){ i=0; j++ }...

This makes code look more similar to e.g. itertools-constructs in python where you can easily make products, zips, ... from iterables.


Doing this stops most compilers putting the index variables in registers, with knock on effects on array indexing efficiency.

Not necessarily a bad practice, but something to be aware of.


It really is a bad idea, though, for the other obvious reason. It goes from being something any programmer can figure out immediately to something that requires additional thought to understand.

The only upside is that it satisfies someone's indentaphobia. No, thank you.


Not really a bad idea, imo. The upside is that you cannot make a stupid typo in these nested loops, which is really easy to do, when you have to write the same thing several times in several places of your program. Also, it is easier to refactor, when the need will be.


The biggest problem I see in doing this is that since C++ does not have yield statements / coroutines / continuations you need to write the iterator code "inside out" and with explicit state, something that usually ends up harder to read than a regular nested-for-loop iteration.


Notice that your own post illustrates why this is a bad idea; whereas

    for(int i=0;i<N;i++){
    }
correctly steps through `N` `i`-values, a version with your `all_frob_indices` would step through `N + 1` `i`-values (because your termination check is `i > N`). Of course, it's easy to fix this once it's spotted, but you won't spot it with the same ease that you'd spot an off-by-one error in a `for` loop, because your eyes (or at least my eyes) don't know how an `all_frob_indices` function should look as well as they do how a `for` loop should look.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: