Swap Algorithm in C Language: Addition and Subtraction Method with Overflow Prevention

Swap Algorithm in C Language: Addition and Subtraction Method with Overflow PreventionSwap Algorithm: Addition and Subtraction MethodIn the previous chapters, we introduced the temporary variable method in the C language swap algorithm, which is a relatively basic method. However, it requires defining a temporary variable to temporarily store the value at the memory address pointed to by the parameters (pointers), which necessitates an extra memory space.The addition and subtraction method introduced here does not require additional memory space, but it does require overflow prevention. The specific implementation can be referenced in the example code below.Example Code for Addition and Subtraction Method

bool __builtin_add_overflow(type a, type b, type *res)

This function is a built-in function in some GCC and Clang compilers, which can be used to detect whether the addition of integers will cause an overflow.

#include <stdio.h>
#include <limits.h>
void swapNumber(int *a, int *b) {
    if( a == b ) return;
    int sum;
    if(__builtin_add_overflow(*a, *b, &sum)){
        printf("Integer overflow!\n");
        return;
    }
    *a = *a + *b;
    *b = *a - *b;
    *a = *a - *b;
}
int main() {
    int x = 255;
    int y = 166;
    swapNumber(&x, &y);
    printf("After swapping values using addition and subtraction: x = %d, y = %d\n", x, y);
    return 0;
}

The code compiles and runs, producing the output:

After swapping values using addition and subtraction: x = 166, y = 255

Disclaimer: The content is for reference only!

Leave a Comment