Question Details

No question body available.

Tags

c assembly compiler-optimization integer-overflow

Answers (3)

Accepted Answer Available
Accepted Answer
December 30, 2025 Score: 20 Rep: 109,636 Quality: Expert Completeness: 80%

You can use C23 Checked Integer Arithmetic (see C23 7.20)

If these type-generic macros return false, the value assigned to result correctly represents the mathematical result of the operation. Otherwise, these type-generic macros return true. In this case, the value assigned to result is the mathematical result of the operation wrapped around to the width of *result.

Example:

#include 
#include 
#include 
int main(void) {
    int res;
    if (ckdadd(&res, INTMAX, INTMAX)) printf("wrap around ==> ");
    printf("%d\n", res);

long long llres; if (ckdadd(&llres, INTMIN, INTMIN)) printf("wrap around ==> "); printf("%lld\n", llres); }

https://godbolt.org/z/zWd9c31Wf

December 30, 2025 Score: 25 Rep: 233,857 Quality: High Completeness: 40%

Why not just use inline assembly and check whether the operation overflows/underflows?

Because the code you link to was written with a goal of being portable: It should work in diverse C implementations. So its author preferred to use code that is strictly conforming to the C standard.

Using inline assembly fails this goal in two ways:

  • Inline assembly is an extension specific to certain compilers. It is not specified by the C standard and is not available in all C implementations.
  • Assembly language varies from platform to platform, so, even when inline assembly is supported by a compiler, the assembly used is not portable between different architectures.
December 31, 2025 Score: 5 Rep: 1,835 Quality: Medium Completeness: 30%

They do, but not in the general-purpose code you're likely to see in libraries

I'm an embedded software engineer, which means I have to care about how long things take to run, because we have real-world things like motors being controlled. If processing takes too long, we won't get a response for the control loop before the next set of input samples arrive. The nature of what I do also means we know exactly what platform is being used.

Because of this, I can and do use all the available features of the processor. It's generally true to say that a good embedded software engineer knows how to manipulate the compiler to leverage the instructions available on the processor: and knows when to drop into assembly operations to get those instructions (or compiler-specific functions which produce those instructions). The resulting code will be completely unportable to other platforms, but portability is rarely a concern.

For authors of general-purpose libraries though, they can make no such assumptions. And this is the kind of code which you're likely to be downloading.