← 講座に戻る: C programming from scratch

Arithmetic, relational, logical and bitwise operators

動画は近日公開

Operators are the symbols that combine values to produce others: adding, comparing, deciding. C has few of them, but each hides details worth knowing. This lesson covers the ones you will use daily and points out the classic traps, above all integer division, the confusion between = and ==, and precedence.

Arithmetic

You have +, -, *, / and % (remainder). Division between two integers discards the decimal part: 7 / 2 is 3, not 3.5. To get decimals at least one operand must be real: 7 / 2.0 is 3.5. The % operator only works with integers, and its sign follows the dividend: -7 % 3 is -1. Dividing or taking the remainder by zero is undefined behavior for integers, so check the divisor first.

c
#include <stdio.h>

int main(void) {
    int a = 7, b = 2;
    printf("%d + %d = %d\n", a, b, a + b);
    printf("%d / %d = %d (integer division)\n", a, b, a / b);
    printf("%d %% %d = %d\n", a, b, a % b);
    printf("%d / 2.0 = %.2f\n", a, a / 2.0);
    printf("-7 %% 3 = %d\n", -7 % 3);
    return 0;
}

Assignment, increment and decrement

The symbol = assigns: it stores the value on the right in the variable on the left. There are compound forms such as +=, -=, *= and /=, which shorten x = x + 5 into x += 5. The operators ++ and -- add or subtract one. Placed before (++x) the change happens before the value is used; placed after (x++) the original value is used and then it changes. Avoid mixing several ++ on the same variable in one expression, because the result can be undefined.

c
#include <stdio.h>

int main(void) {
    int x = 5;
    int y = x++;   /* y = 5, then x = 6 */
    int z = ++x;   /* x = 7, then z = 7 */
    printf("x=%d y=%d z=%d\n", x, y, z);

    x += 10;       /* x = 17 */
    x %= 5;        /* x = 2 */
    printf("x=%d\n", x);
    return 0;
}

Relational and logical

The operators ==, !=, <, >, <= and >= compare and return an int: 1 if true and 0 if false. In C any nonzero value counts as true. To combine conditions use && (and), || (or) and ! (not). The first two use short-circuit evaluation: if the result is already known from the left side, the right side is not even evaluated. This lets you write b != 0 && a / b > 2 without risk of dividing by zero.

Bitwise operators and precedence

Bitwise operators work on the binary representation: & (AND), | (OR), ^ (XOR), ~ (NOT) and the shifts << and >>. They are useful for flags and protocols. Shifting a number left is equivalent to multiplying by powers of two. About precedence, multiplication goes before addition and comparisons before logical operators, but bitwise ones have lower precedence than ==, which surprises people: flags & 4 == 4 is evaluated as flags & (4 == 4). When in doubt, use parentheses.

c
#include <stdio.h>

int main(void) {
    unsigned int flags = 0;
    flags |= 1u << 2;          /* set bit 2 */
    flags |= 1u << 0;          /* set bit 0 */
    printf("flags = %u\n", flags);            /* 5 */

    if ((flags & 4u) == 4u) {                 /* parentheses needed */
        printf("bit 2 is on\n");
    }
    flags &= ~1u;              /* clear bit 0 */
    printf("flags = %u\n", flags);            /* 4 */
    printf("6 ^ 3 = %d\n", 6 ^ 3);           /* 5 */
    return 0;
}

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →