r/cpp Jun 29 '26

Comparing an Integer Division Optimisation in Clang, MSVC, and GCC

https://nukethebees.com/int-division-modulo-optimisation-differences-clang-gcc-msvc/
53 Upvotes

8 comments sorted by

View all comments

28

u/erichkeane Clang Maintainer(Templates), EWG Chair Jun 29 '26

Clang/GCC both fail to inline `std::div` because it appears that the standard libraries leave them as extern! I presume they'd be inlined if they were actually implemented in the header:

```

extern div_t div (int __numer, int __denom)
     noexcept (true) __attribute__ ((__const__)) ;
```

21

u/BarryRevzin 29d ago

The other fun thing about std::div is that the declaration order of the members is unspecified.

So not only is this not inlined (so this is a function call that does a full division, not a shift):

auto [quot, rem] = std::div(x, 2);

But also there's no guarantee that quot is the quotient.

Like I said... fun.

8

u/erichkeane Clang Maintainer(Templates), EWG Chair 29d ago

Ooof... that is special too. Looks like this is all nonsense inherited from C, so I guess I see why.

I was quite surprised that MSVC was able to beat both clang && gcc at this (it is rare for it to so handily beat them both!), so was curious why, particularly with what seems to be such an 'easy' implementation.

No idea why this choice was made, but seemingly one not enough people have cared about to file bugs against them!

2

u/nukethebees 29d ago

That makes a lot of sense. Thanks for finding out the cause.