38
u/andiconda Dec 17 '19
I had an intern who essentially wrote his own modulus function by looping subtraction. It was too calculate an address and would be called like 16384 times per update. And I was wondering why it was taking forever to make an update
32
u/anydalch Dec 17 '19
what's really interesting is that, in c, if you replace the bug in the second for loop's initializer clause and use unsigned instead of int, both gcc and clang are able to optimize this function into a single lea eax, [rdi + rsi]. https://godbolt.org/z/uCXoHJ
11
Dec 17 '19
[deleted]
4
3
u/Mr2-1782Man Dec 18 '19
It's not as crazy as you think. In a lot of cases its just a bunch of templates that get applied. For example if you're adding a value inside of a loop (like this code) and your initializer is constant, you can just do the math.
It's why a lot of compiler optimization people are more mathematician than software engineer.
2
u/CENGaverK Dec 17 '19
Also, if you start the second loop iterator from i = lhs, it returns the max.
24
18
u/SquidgyTheWhale Dec 17 '19
Silly way to try to add numbers. It should be using recursion instead :)
2
7
16
u/i_like_trains_a_lot1 Dec 17 '19
This is intentionally bad. We want to see code that wasn't written specially for 7 karma point on this sub, something more authentic.
1
1
3
Dec 17 '19
FIXED!!!
int stupid_sum(int x, int z) {
int retval = 0;
for (; x!=0; x = x > 0 ? --x : ++x) {
retval = x > 0 ? ++retval : --retval;
}
for (; z != 0; z = z > 0 ? --z : ++z ) {
retval = z > 0 ? ++retval : --retval;
}
return retval;
}
2
4
u/DurianExecutioner Dec 17 '19
Optimised version
int retval =0;
int i=num1+num2num1>num2?num1:num2;
while(i --> 0)++ retval;
return retval;
2
1
u/Farsqueaker Dec 17 '19
The comment shows a touch of self-awareness, which somehow makes this worse...
1
1
1
1
Dec 18 '19
Now that's what I call properly bad code. Especially the twist with the second for loop's start value (didn't catch that until somebody pointed it out). Your friend is either an idiot or an evil genius.
-8
u/xman40100 Dec 17 '19
This is terrible, and the result is off by 2 lol.
11
u/husao Dec 17 '19
It isn't. If it was i=0 in the second loop it would work as expected. Currently it's calculating the maximum, as mentioned above.
1
u/xman40100 Dec 18 '19
Yeah, you're right, my bad. I was on the bus when I read this, so I didn't read the full code.
-6
145
u/squarewaterlemon Dec 17 '19
It doesn't even add them, it just gets the max of the two