| Binary plus and minus operators ('+' and '-')

| Binary operators | Next

Both `'+'` and `'-'` uses the same syntax:

    expr1 + expr2
    expr1 - expr2

Note that both '+' and '-' operators also have an unary form.
Legal operand types for expr1 + expr2 are:

1. Both expr1 and expr2 are of arithmetic type;
2. expr1 is of pointer to object type, and expr2 is of integral type.
3. expr1 is of integral type, and expr2 is of pointer to object type;

In case 1, the operands are subjected to the standard arithmetical conversions (for example, `char`s are promoted to `int`s), and the result is the arithmetical sum of the operands.
In cases 2 and 3, the rules of pointer arithmetic apply. When expr1 is of pointer type (case 2), the actual address on which a pointer points to is incremented by expr2 multiplied by the size of the pointed object (not just by expr2, except if the pointed object is one byte long). For example, if expr1 points to an array, expr1 + 5 points to a fifth element of the array, no matter how long are the particular elements of the array. The same rules are valid for the case 3. Assuming that ptr is a pointer to type and that N is an integer, and assuming that the CPU uses linear addressing (this is true on Motorola 68000, but not on Intel 8086 for example), expression

    ptr + N

is equal to

    (type *) ((long) ptr + N * sizeof (type))

Legal operand types for expr1 - expr2 are:

1. Both expr1 and expr2 are of arithmetic type;
2. expr1 is of pointer to object type, and expr2 is integral type;
3. Both expr1 and expr2 are pointers to compatible object types;

In case 1, the operands are subjected to the standard arithmetic conversions, and the result is the arithmetic difference of the operands.
In cases 2 and 3, the rules of pointer arithmetic apply. When expr1 is pointer and expr2 is integral type (case 2), the actual address on which a pointer points to is decremented by expr2 multiplied by the size of the pointed object (not just by expr2, except if the pointed object is one byte long). For example, if expr1 points to the fifth element of an array, expr1 - 2 points to a third element of the array, no matter how long are the particular elements of the array. When both expr1 and expr2 are pointers, the result of the substraction is the difference of actual addresses divided by the common size of pointed objects. For example, if expr1 and expr2 point to two elements of the same array, then expr2 - expr1 will be equal to the difference of actual indices of pointed elements.
The unqualified type 'type' is considered to be compatible with the qualified types 'const type', 'volatile type', and 'const volatile type'.
Floating point addition and substraction are internally executed using the fadd and fsub functions.
Note: GNU C extends the pointer arithmetic to be valid even on void pointers and pointers to functions (see extended pointer arithmetic for more info).