r/shittyprogramming • • May 03 '17

I love while loops

Post image
285 Upvotes

77 comments sorted by

66

u/Laat May 03 '17

A case could be made that k is "leaking" into the block-scope after the for/while loop is finished. In that case (if this works in C), this would be better:

public int fun4(int n)
{
    int product = 1;
    for(int k = 2; k <= n; ++k)
    {
        product *= k;
    }
    return product;
}

99

u/Nialsh May 03 '17

Always remember to save variables by mutating parameters.

public int fun5(int n)
{
    int product = 1;
    while (n > 1)
    {
        product *= n--;
    }
    return product;
}

Save your variables for another day!

43

u/[deleted] May 03 '17

This is how good assembly code gets written.

19

u/UsablePizza May 03 '17

I heard that compilers are smart enough to know that's pretty much what you mean to do and do that for you.

6

u/[deleted] May 03 '17

They say that. I have always experienced the opposite. My assembly always beats the VS2015 Compiler by every metric (it doesn't even prediction optimize most branches).

6

u/Famous1107 May 03 '17

What about the time it takes to write a program?! Just kidding.

2

u/jarfil May 03 '17 edited Dec 02 '23

CENSORED

3

u/Rangsk May 03 '17

Are you comparing against the standard optimizer or against the profile guided optimizer?

1

u/[deleted] May 03 '17

Standard. Never tried another.

5

u/Rangsk May 03 '17

I ask because the profile guided is supposed to add branch predictions.

1

u/shinyquagsire23 May 03 '17

I thought everyone knew VS compiler optimisation was a joke by this point

1

u/pigeon768 May 04 '17

VS2015 Compiler

Well... yeah

https://godbolt.org/g/d0Vjhy

20

u/SomeInternetStranger May 03 '17
int fun(int n) {
    int product = 1;
    for (; n > 1; product *= n--);
    return product;
}    

For loops for life!

4

u/jaxklax May 03 '17

Good as an intellectual exercise, bad to do in real programs.

1

u/nakilon May 04 '17

If you replace here for with while you'll get totally nice K&R style.

4

u/audioB May 03 '17

wtf can you do this...

 

rewrites everything

2

u/AprilSpektra May 03 '17

Uh, yes? In any language that passes by value (such as C and C++, although C++ can also pass by reference), a function parameter simply creates a new copy of the value in the function call's stack frame. As with all variables in the function's scope, this copy will go away once the function goes out of scope, so you can do whatever you want with it.

12

u/AnimalFarmPig May 03 '17

One fewer variable--

public int fun6(int n)
{
    if (n <= 1) { return 1; }
    return n * fun6(n - 1);
}

2

u/three18ti May 04 '17

so then wouldn't this work:

public int fun7(int n) { return n <=1 ? 1 : n * fun6(n - 1); }

0

u/[deleted] May 03 '17

[deleted]

15

u/Intrexa May 03 '17

Yes, and more, a lot more gets pushed onto the stack as book keeping.

3

u/Marzhall May 03 '17 edited May 03 '17

Edit: Whoops, took too short a glance before replying - u/noop_noob is correct, this wouldn't be covered under tail-call optimization.

It depends on your compiler and optimization settings, but you'd probably end up with the same result, actually. GCC, for example, would likely perform "tail-call optimization," turning the recursive call into a loop in the final assembly.

So a naive compiler who went by the 'letter of the law' would have the problem you mention, but an optimizing compiler would likely recognize that it could just be turned into a loop, meaning you've effectively written a fancy-looking loop at the end of the day.

7

u/noop_noob May 03 '17

This is not a tail call.

3

u/AnimalFarmPig May 03 '17

Yep. Last call in the function is the multiplication operation. If the function were re-written to accept n and an accumulator, then we could tail call, but this is /r/shittyprogramming.

1

u/edave64 May 03 '17

Pretty sure all of the above create the exact same code with decent compiler optimization.

3

u/squidgyhead May 04 '17

If you do /u/Laat's method, one could throw an

#pragma omp parallel for shared(product,) reduction(*: product)

before the for loop and then it'll be parallel. Should be able to throw simd stuff in there too.

While saving variables is good, and I like the way that /u/Nialsh wrote it, a more standard style can allow for more flexibility: since it's standard, compiler writers have focused on it, after all!

2

u/pigeon768 May 04 '17 edited May 04 '17

Always remember to save a cmp instruction in your inner loop by comparing to zero after an arithmetic instruction.

int fun6(int n) {
  int product = 1;
  while(n)
    product *= n--;
  return product;
}

fun5(int):
    mov     eax, 1
    cmp     edi, 1
    jle     .L4
.L3:
    imul    eax, edi
    sub     edi, 1
    cmp     edi, 1            # useless instruction
    jne     .L3
    ret
.L4:
    ret
fun6(int):
    mov     eax, 1
    test    edi, edi
    je      .L11
.L10:
    imul    eax, edi
    sub     edi, 1
    jne     .L10
    ret
.L11:
    ret

Think about all those poor useless instructions, cursed to live a life useless drudgery.

1

u/jantari May 03 '17

Sorry I don't understand this, if it's serious advice can you explain why it's better please

1

u/Nialsh May 03 '17

We're in /r/shittyprogramming and unless you're performing low-level optimizations, mutation is bad style because it makes programs harder to reason about. In particular, parameters should be treated as read-only.

9

u/accatyyc May 03 '17

That does work in C, but the "public" makes me believe that the code is actually Java

7

u/absurdlyinconvenient May 03 '17

Variables can be defined in a for loop in Java as well

2

u/YM_Industries May 03 '17

Could be C#, but you can define the variable within the for loop there too.

1

u/Intrexa May 03 '17

I took 'fun' to mean 'function', which makes me think c++, cuz java only has methods.

2

u/jarfil May 03 '17 edited Dec 02 '23

CENSORED

1

u/noop_noob May 03 '17

Fun fact, "function" can also be a verb.

1

u/VincentDankGogh May 03 '17

It doesn't work in C89 actually, although I don't think it's used by many people anymore.

1

u/DrNightingale May 03 '17

I use it and I believe it's still common in embedded development.

1

u/VincentDankGogh May 03 '17

Why is that? Do you prefer it stylistically or is it that the compiler you use doesn't support C99?

1

u/DrNightingale May 03 '17

The latter. I use armcc which only supports C89.

1

u/Zatherz May 04 '17

Why not GCC?

2

u/DrNightingale May 04 '17

It's just more convenient for embedded development. Keil, the IDE that uses armcc, has tons of support for different microcontrollers out of the box. With gcc, the support for arm controllers isn't great and you have to configure everything yourself.

1

u/wiskinator May 04 '17

This works in modern C.

18

u/taji34 May 03 '17

I shit you not, there is a professor at my University that I TA for who advocates using while loops instead of for loops in all cases. We're working in Java for that class, and it's frustrating because it just leads to more students forgetting to increment their counter or something and getting infinite loops.

20

u/jarfil May 03 '17 edited Dec 02 '23

CENSORED

4

u/taji34 May 03 '17

In theory, yes, but in practice it doesn't work. At least not the way he does it. Furthermore, he encouraged while loop use over for loops in every case, and all of his examples use while loops exclusively, which has the result that students don't learn how to use for loops properly and never use them themselves.

While I agree, forcing them to use while loops for a homework assignment or on a test would be beneficial in teaching them about their counters it should be limited to that. A single assignment or test, not the whole course.

2

u/zoells May 04 '17

UMN?

2

u/taji35 May 04 '17

Yep

1

u/here-to-jerk-off May 05 '17

what's going on here? these accounts are 3 and 4 years old, but off by 1?

2

u/Renown84 May 14 '17

alts

1

u/taji34 May 24 '17

No, actually, unimaginative twins.

1

u/jesse_dev May 24 '17

In other words, you mean:

while (iAgree()) { 
    if (endOfCourse()) {
        break;
    } else {
        force('use of while loops');
    }
}

13

u/potterhead42 May 03 '17

needsmorejpeg

1

u/ArgueWithMeAboutCorn May 03 '17

That's Drakes brother, Drork

6

u/faubiguy May 03 '17

Needs more recursion.

public int fun3(int n)
{
  if (n < 2)
  {
    return 1;
  }
  else
  {
    return n * fun3(n - 1);
  }
}

10

u/prof_hobart May 03 '17

Needs more ternary

public int fun4(int n) {
    return n<2 ? 1 : n * fun4(n - 1);
}

5

u/Illusi May 03 '17

Code lasts longer when you print it out. Protects against bit rot.

5

u/Nikolai-Agnon May 03 '17

While you're at it...

product *= k++;

e: Or, if you're like me and are a fan of inverted iterations,

int k = n;
while (k) {
    product *= k--;
}

3

u/RocketLeague May 03 '17

I don't get it...

4

u/RadioactivMango May 03 '17

He likes while loops, not for loops. (possible shittyness because for loops are useful)

3

u/cediddi May 03 '17

Foreach>while>for

3

u/dragonice81 May 03 '17

DoWhile>ForEach>While>For

3

u/cediddi May 04 '17

Yeah, that is better :)

3

u/outadoc May 03 '17

not using tail recursion in a functional language

1

u/sintos-compa May 04 '17

i've been coding since 1980s and i am slightly ashamed about how often i forget to iterate the loop counter in a while loop (while never forgetting it in a for loop)

1

u/Ultimater May 21 '17

Both are terrible. Factorials grow really quick and you're using int...

1

u/jamesh1999 Jun 07 '17 edited Jun 07 '17
public int fun(int n)
{
	for(int k = n; k; n *= --k) ;
	return n;
}

Pretty golfed now

:)

1

u/fib0nacci112358 Jun 23 '17

Better than writing loops with just jumps. cough assembly cough

-16

u/hunyeti May 03 '17 edited May 03 '17

and what's shitty about this?

the for loop above is in fact, a horrible concept.

EDIT: Geez guys, forgot which subreddit is this? you supposed to upvote this.

13

u/[deleted] May 03 '17

no, why?

1

u/MyPhallicObject May 25 '17

I must agree, the C style for loop is a horrible concept. It requires three statements and a throwaway variable just to iterate a counter.

Swift has done it correctly: for _in 1...10. Simple, and no additional variables.

10

u/ElectricalAlchemist May 03 '17

They parsed your comment as it was. If you wanted to guarantee correct translation you should have used the sarcasm modifier.

4

u/hunyeti May 03 '17

It's not sarcasm, it's /r/shittyprogramming

2

u/three18ti May 04 '17

And now the story of one Reddit fully of shitty programmers and the one Redditor who had to keep them all together. Iiiittt'sss....

2

u/[deleted] May 04 '17

Don'tevenneedalexer / parsergenerator,justhand - rollyourownsarcasmparserafterstrippingoutallwhitespace

Error line 1: unmatched single quote

0

u/MiningPotatoes May 03 '17

needs more AP Comp Sci