Search code examples
cintegerinteger-overflow

Integer overflow test operator? (&+)


This question could just be another case of interpreting the operator incorrectly. But a while ago, I saw someone tweeting about an operator that allegedly can be used to check for integer overflow in C. Namely the &+ (ampersand-plus) operator, and it could be used simply like so:

#include <stdio.h>
#include <stdint.h>

int main()
{
    uint32_t x, y;

    x = 0xFFFFFFFF;
    y = 1;

    if (x &+ y) {
        printf("Integer overflow!\n");
    } else {
        printf("No overflow\n");
    }

    return 0;
}

It does seem to work as one would expect, and GCC 6 doesn't throw me any warnings or errors when compiling it with these parameters: gcc -Wall -Wextra -Werror of.c

But oddly enough, I have yet to find any documentation about this operator, and I never saw it used anywhere. Could someone please explain how this works?


Solution

  • The expression

    x &+ y
    

    is parsed as

    x & (+y)
    

    using the unary plus operator, which has no effect (in this case) and just returns y. That means the expression is equivalent to

    x & y
    

    which does not test for integer overflow and instead just checks if x and y have any bits in common. Try changing x and y to 1 and see what happens; it'll report an overflow even though none will occur.