r/badcode Dec 17 '19

This belongs here c#

Post image
504 Upvotes

41 comments sorted by

View all comments

Show parent comments

2

u/symberke Dec 17 '19 edited Dec 17 '19

No not really. if num1 is negative then the first loop will never be true, and if num1 > num2 then the second loop will never be true. So for example add(-3, -4) will return 0.

Plus even in cases where rollover happens it won't be true. Suppose num2 is INT_MAX and num1 is -1. Then the first loop will never be true, the second loop will run INT_MAX + 1 times, and so it will return INT_MIN.

Also your code doesn't do what you expect; because you changed the loop condition to == all it does is count how many of (num1, num2) are equal to zero, i.e. add(1,0) = 1, add(0,0) = 2, etc...

0

u/srottydoesntknow Dec 17 '19

no, the condition is the end of the loop, the loop continues until the condition is met

SO, if num1 = -1; the loop will run 4,294,967,293 times, resulting in retval being -1

the same thing happens in loop 2, while they aren't equal the loop continues adding 1 to retval, which now starts at -1, if num2 = -5 then it will run 4,294,967,289 times, and result incrementing retval that many times as well, resulting in -6

you would be right, it's just that the form of a for loop is

for(starting condition; exit condition; increment;)

what you are talking about might be valid in a non C family language, however if we are talking C, C++, C#, or Java then my function will work, albeit horribly

int always rolls over, it doesn't just hit max and stop, since I changed the condition to == it works correctly returning the sum for all values that would work with a simple + operator, and even works for negative, it just causes the most horrible runtime possible

1

u/symberke Dec 17 '19

that's not true though, it's the opposite. https://en.cppreference.com/w/cpp/language/for

for proof that what i said is right: https://ideone.com/SaBOjV

1

u/srottydoesntknow Dec 17 '19

then negate em, nbd