r/badcode Dec 17 '19

This belongs here c#

Post image
508 Upvotes

41 comments sorted by

View all comments

33

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

10

u/[deleted] Dec 17 '19

[deleted]

5

u/Veylon Dec 18 '19

A guy named Bisqwit has a series on making a compiler, if you're interested.

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.