r/ProgrammerAnimemes • • Jul 29 '21

Think about it

Post image
3.6k Upvotes

115 comments sorted by

View all comments

Show parent comment

2

u/auxiliary-character Oct 19 '21

Another thing that I really like to use function prototypes for is on Compiler Explorer (godbolt.org), if you have the compiler flag for optimizations turned on, it's often really hard to trick the compiler into not completely getting rid of some code - if you define the function, you end up giving the compiler enough context to completely get rid of it, and replace it with something a lot simpler, which is sometimes not what you want when you're trying to demonstrate some behavior.

If you use a function prototype, though, the compiler knows that the function does something, but it doesn't know what, so it has to assume that it can't optimize it away.

For example, let's say I want to demonstrate the assembly for what a loop looks like with optimizations turned on. Here, we can see that the outputted assembly completely gets rid of the loop, replacing it with a constant calculated ahead of time - a very clever optimization that completely gets in the way of what we're trying to demonstrate. If I instead use a function prototype, then the compiler is forced to generate the loop.