SyntaxStudy
Sign Up
C Arithmetic and Assignment Operators
C Beginner 1 min read

Arithmetic and Assignment Operators

C's arithmetic operators cover the standard operations: `+` (addition), `-` (subtraction), `*` (multiplication), `/` (division), and `%` (modulo). Division between two integers performs integer division, discarding any remainder. The modulo operator returns the remainder and is defined for integer operands only. Operator precedence follows standard mathematical conventions, and parentheses can override precedence. Assignment in C uses `=`. Compound assignment operators combine an arithmetic operation with assignment: `+=`, `-=`, `*=`, `/=`, and `%=`. These are shorthand and produce identical code to the expanded form. The increment operator `++` adds one to a variable; `--` subtracts one. Both have prefix and postfix forms that differ in when the updated value is made available in an expression. The comma operator evaluates two expressions left-to-right and returns the value of the right operand. It is most commonly used in `for` loop headers to update multiple variables. Using the comma operator outside of `for` loops tends to reduce readability and should generally be avoided in favour of separate statements.
Example
#include <stdio.h>

int main(void)
{
    int x = 10, y = 3;

    printf("x + y  = %d\n", x + y);   /* 13 */
    printf("x - y  = %d\n", x - y);   /* 7  */
    printf("x * y  = %d\n", x * y);   /* 30 */
    printf("x / y  = %d\n", x / y);   /* 3  (integer division) */
    printf("x %% y  = %d\n", x % y);  /* 1  (remainder) */

    /* Compound assignment */
    x += 5;   printf("x += 5  -> %d\n", x);  /* 15 */
    x -= 3;   printf("x -= 3  -> %d\n", x);  /* 12 */
    x *= 2;   printf("x *= 2  -> %d\n", x);  /* 24 */
    x /= 4;   printf("x /= 4  -> %d\n", x);  /* 6  */
    x %= 4;   printf("x %%= 4  -> %d\n", x); /* 2  */

    /* Prefix vs postfix increment */
    int a = 5;
    printf("a++ = %d  (a is now %d)\n", a++, a); /* 5, then 6 */
    printf("++a = %d\n", ++a);                    /* 7          */

    /* Comma operator in for loop */
    int i, j;
    for (i = 0, j = 10; i < 3; i++, j--) {
        printf("i=%d  j=%d\n", i, j);
    }

    return 0;
}