C basics · 3 of 8

Casts, operators and precedence

How C parses expressions such as a & b == c and *p++, what a cast changes, and which expressions are undefined.

1Read

C reads an expression as a tree

An expression such as 2 + 3 * 4 mixes several operators. Before working anything out, C decides which operator takes which values. It builds a tree: each operator sits above the two things it works on, and the values are worked out from the bottom up.

No brackets

2 + 3 * 4
+142*1234

Result: 14 (int)

With brackets

(2 + 3) * 4
*20+5234

Result: 20 (int)

* grabs its two neighbours before + does, so 2 + 3 * 4 is 2 + (3 * 4), which is 14. Brackets build a different tree. This rule, which operator grabs first, is called precedence.

The precedence ladder

Every C operator sits on one rung of a ladder. Higher rungs grab their operands first. When two operators share a rung, most group left to right: a - b - c is (a - b) - c. The three rungs marked "right to left" group the other way, so a = b = 0 stores 0 in b, then in a.

LevelOperatorsExampleC reads it as
1 After a valuea[i]x++x--*p++*(p++)
2 Before a valuegroups right to left++x--x-x!x~x*p&x(type)xsizeof(double)a / b((double)a) / b
3 Multiply, divide*/%2 + 3 * 42 + (3 * 4)
4 Add, subtract+-a - b - c(a - b) - c
5 Shifttrap: lower than + and −<<>>x << 1 + 1x << (1 + 1)
6 Compare<<=>>=3 > 2 > 1(3 > 2) > 1
7 Equal, not equal==!=x & 1 == 0x & (1 == 0)
8 Bitwise ANDtrap: lower than ==&x & 1 == 0x & (1 == 0)
9 Bitwise XORtrap: lower than ==^a ^ b == ca ^ (b == c)
10 Bitwise ORtrap: lower than ==|a | b == ca | (b == c)
11 Logical AND&&a && b || c(a && b) || c
12 Logical OR||a || b && ca || (b && c)
13 Choosegroups right to left? :a ? b : c ? d : ea ? b : (c ? d : e)
14 Assigngroups right to left=+=-=*=&=|=<<=…a = b = 0a = (b = 0)
15 Comma,i++, j++(i++), (j++)

You do not need to learn all of it. The rows that cause real bugs are marked: the bit operators &, ^ and | sit below ==, and the shifts << and >> sit below + and −. Both feel backwards, and both turn up constantly in code that reads hardware registers.

Trap 1: & comes after ==

To check whether a number is even, you look at its lowest bit. This looks right:

int x = 4;

As written

x & 1 == 0
&0x4==010

Result: 0 (int)

gcc -Wall warning: suggest parentheses around comparison in operand of ‘&’

With brackets

(x & 1) == 0
==1&0x410

Result: 1 (int)

== grabs first, so C works out 1 == 0, which is 0 (false). Then x & 0 is 0, whatever x is. The check is always false. The same thing happens to reg & MASK == MASK in register code. GCC warns about it when you build with -Wall.

Trap 2: comparisons do not chain

In maths, 3 > 2 > 1 is true. In C, it is false:

As written

3 > 2 > 1
>0>1321

Result: 0 (int)

gcc -Wall warning: comparisons like ‘X<=Y<=Z’ do not have their mathematical meaning

What maths means

3 > 2 && 2 > 1
&&1>132>121

Result: 1 (int)

C groups it as (3 > 2) > 1. 3 > 2 is 1 (true), and 1 > 1 is 0. To check that a value lies between two others, write two comparisons joined with &&.

Trap 3: shifts come after +

int x = 3;

As written

x << 1 + 1
<<12x3+211

Result: 12 (int)

gcc -Wall warning: suggest parentheses around ‘+’ inside ‘<<’

With brackets

(x << 1) + 1
+7<<6x311

Result: 7 (int)

+ grabs first, so this shifts x by 2. When you build a value from bytes, hi << 8 + lo shifts hi by 8 + lo, which is almost never what you meant.

Trap 4: *p++ moves the pointer

p++ and *p are both on high rungs, but the operators written after a value (p++, a[i]) sit one rung above those written before it (*p, -x, !x). So in *p++, the ++ belongs to p.

uint8_t buf[3] = {10, 20, 30};
uint8_t *p = buf;      /* p points to buf[0] */
You writeC reads it asValuebuf afterwardsp afterwards
*p++*(p++)10{10, 20, 30}points to buf[1]
(*p)++(*p)++10{11, 20, 30}points to buf[0]
++*p++(*p)11{11, 20, 30}points to buf[0]
*++p*(++p)20{10, 20, 30}points to buf[1]

p++ gives the old address and then moves p, so *p++ reads the current element and steps to the next one. That is the classic way to walk through an array. To add 1 to the value instead, write (*p)++.

One more: if (x = 5)

= stores a value; == compares. if (x = 5) stores 5 in x, and since 5 is not 0 the test is always true. GCC with -Wall says "suggest parentheses around assignment used as truth value".

Casts: changing the type on purpose

A cast is a type name in brackets in front of a value: (double)a gives the value of a as a double. A cast sits on the same high rung as -x and !x, so it applies only to the value right after it:

int a = 7, b = 2;

As written

(double)a / b
/3.5(double)7.0a7b2

Result: 3.5 (double)

Cast after dividing

(double)(a / b)
(double)3.0/3a7b2

Result: 3.0 (double)

In (double)a / b, a becomes 7.0 first. One side of / is now a double, so b is converted too and the division keeps the fraction: 3.5. In (double)(a / b) the brackets make the division happen first, between two ints, so the fraction is already gone: 3.0.

What a cast does to the value depends on the two types:

CastResultWhy
(int)3.993The fraction is dropped. It does not round to 4.
(int)-3.99−3Dropping the fraction moves toward zero, so −3, not −4.
(uint8_t)30044Only the lowest 8 bits are kept: 300 is 1 0010 1100, the low 8 bits are 44.
(int8_t)200−56Too big for int8_t. C leaves it to the compiler; GCC keeps the bits, which read as −56. GCC's choice
(unsigned)-14,294,967,295Converting to unsigned wraps around: −1 becomes the largest unsigned int.
(uint8_t)a + bwith uint8_t a = 200, b = 100300The cast applies to a only. a + b is then worked out as an int.
(uint8_t)(a + b)with uint8_t a = 200, b = 10044Now the cast applies to the sum, 300, and keeps the low 8 bits.

The last two rows are lesson 2 again: a cast to uint8_t keeps the lowest 8 bits, and math on small types happens in int.

Whole-number division rounds toward zero

When both sides are whole numbers, / drops the fraction, moving toward zero: 7 / 2 is 3 and −7 / 2 is −3, not −4. % gives what is left over, with the same sign as the left side, so that (a / b) * b + a % b always equals a:

aba / ba % bcheck: (a / b) * b + a % b
72317
−72−3−1−7
7−2−317
−7−23−1−7

Dividing by 0 is undefined, and so is INT_MIN / -1, because the answer, 2,147,483,648, does not fit in an int.

A floating value that does not fit

Casting a double to an integer type drops the fraction. If what is left does not fit in that type, C does not say what happens, even for unsigned types. Compare (uint8_t)300, which is defined and gives 44, with (uint8_t)300.0, which is undefined. Here is the same GCC on two chips:

CastARM64PC (x86-64)
(uint8_t)300.0 Undefined4444
(uint8_t)-1.0 Undefined0255
(int)3e10 Undefined2,147,483,647−2,147,483,648

On both chips GCC first converts to a 32-bit integer, then keeps the low byte for uint8_t. That is why 300.0 gives 44 on both. The chips differ when the value does not fit in 32 bits. ARM's instruction clamps to the nearest 32-bit value: −1.0 becomes 0 for an unsigned result, and 3e10 becomes the largest int. x86's instruction gives one fixed pattern, 0x80000000, for anything that does not fit in an int; −1.0 does fit, becomes −1, and its low byte is 255. Neither is wrong, because C promises nothing. Check the range before converting.

Precedence is not order

Precedence decides the grouping, not which side is worked out first. In f() + g(), C may call g before f. Usually that does not matter. It matters when one part of an expression changes a variable and another part uses the same variable: then the result depends on an order C never fixed, and the C standard calls it undefined.

ExpressionC saysWhat happens
i = i + 1with int i = 5DefinedGives 6; afterwards i is 6.
i++ && i++with int i = 5DefinedGives 1; afterwards i is 7.
(i++, i++)with int i = 5DefinedGives 6; afterwards i is 7.
i = i++with int i = 5UndefinedGCC on ARM64: i stays 5.
i++ + i++with int i = 5UndefinedGCC on ARM64: 11, and i ends at 7.
i = ++i + 1with int i = 5UndefinedGCC on ARM64: i is 7.
a[i] = i++with int i = 1UndefinedGCC on ARM64: stored 1 in a[2], not a[1].
printf("%d %d", i, i++)with int i = 5UndefinedGCC on ARM64 printed 6 5: it worked out the second argument first.

The GCC results are what GCC 13.3 happened to produce, the same at -O0 and -O2. Nothing guarantees them: another compiler, or the next version of GCC, may give something else.

Four operators do fix an order: &&, ||, ?: and the comma operator always finish their left side before starting the right. That is why i++ && i++ is fine. GCC warns about the undefined rows with -Wall: "operation on 'i' may be undefined".

&& and || can skip their right side

&& stops as soon as its left side is false, because the answer is already known. || stops as soon as its left side is true. The right side is then never worked out:

int x = 0;
x != 0 && 10 / x > 2
&&0!=0x00>skipped/skipped10skippedxskipped2skipped

Result: 0 (int)

So x != 0 && 10 / x > 2 never divides by zero. Code uses this all the time, for example p != NULL && *p == 0 reads *p only when p points somewhere.

2Watch

Step through an expression

Pick an example. The first step shows how C groups the expression; then each step works out one box of the tree, from the bottom up. Variables that change are marked.

Pick an example
int x = 4;
x & 1 == 0

How C groups it1 of 4

gcc -Wall warning: suggest parentheses around comparison in operand of ‘&’

&x==10

Variables

  • xint4
Before working anything out, C decides which operator takes which operands. With every group in brackets, this reads x & (1 == 0). The tree shows the same thing: each operator sits above the parts it works on, and C works from the bottom up.

Try your own

Edit the variables or type any expression that uses them. The tree, the steps and GCC's warning update as you type. You can use the operators from the table, casts to number types, sizeof, arrays and pointers.

reg & 0x04 == 0x04

How C groups it1 of 4

gcc -Wall warning: suggest parentheses around comparison in operand of ‘&’

&reg==0x040x04

Variables

  • auint8_t200
  • buint8_t100
  • xint7
  • yint2
  • iint5
  • regunsigned int12
  • bufuint8_t[3]10[0]↑ p20[1]30[2]
  • puint8_t *points to buf[0]
Before working anything out, C decides which operator takes which operands. With every group in brackets, this reads reg & (0x04 == 0x04). The tree shows the same thing: each operator sits above the parts it works on, and C works from the bottom up.

3Practice

Predict the value

Work out each answer, then press Check. After checking you see the tree.

  1. Q1 Is x even? What does this give?

    int x = 4;
    x & 1 == 0
  2. Q2 What does this give?

    3 > 2 > 1
  3. Q3 What does this give?

    int x = 3;
    x << 1 + 1
  4. Q4 What is d?

    int a = 7, b = 2;
    double d = (double)(a / b);
    d
  5. Q5 Whole-number division with a negative number.

    -7 / 2
    -7 % 2
  6. Q6 Where does the cast apply?

    uint8_t a = 200, b = 100;
    (uint8_t)a + b
  7. Q7 ! and ~ look alike. What do they give?

    !0x10
    ~0x10
  8. Q8 Which moves: the pointer or the value?

    uint8_t buf[3] = {10, 20, 30};
    uint8_t *p = buf;
    int v = *p++;
  9. Q9 How far does || go?

    int i = 0;
    int r = i++ || i++;

How does C group it?

Pick the grouping C uses.

  1. G1 How does C group a + b << 2?

    C reads it as
  2. G2 How does C group a & b == c?

    C reads it as
  3. G3 How does C group !x == y?

    C reads it as
  4. G4 How does C group a = b == c?

    C reads it as
  5. G5 How does C group (int)x / y?

    C reads it as
  6. G6 How does C group a || b && c?

    C reads it as

Defined or undefined?

U1 For each expression, with int i = 5; and an array a: is it defined, or undefined?

i = i + 1
i = i++
i++ && i++
a[i] = i++
i++ + 1
i + i++
(i++, i++)

Challenge: fix the expression

Each expression below was written by someone in a hurry and has a precedence bug. Change it until every test passes. The tests run as you type, and the tree shows how C reads your version.

  1. C1 Is bit 2 set? STATUS is a hardware status register. Write an expression that gives 1 when bit 2 (value 0x04) is set and 0 when it is not. The code below is what a colleague wrote.

    uint32_t STATUS;
    /* your expression */
    Show a hint

    Which goes first, & or ==? Check the table.

    3 of 7 tests pass.

    TestSTATUSExpectedYours
    fail0x410
    pass0x511
    fail0x101
    pass0x000
    pass0xFF11
    fail0xFB01
    fail0xC10

    Test 1 on your expression. C reads it as STATUS & (0x04 == 0x04).

    gcc -Wall warning: suggest parentheses around comparison in operand of ‘&’

    &0STATUS4==10x0440x044
  2. C2 Two bytes into one 16-bit value. A sensor sends its reading as two bytes, high byte first. Combine them into one value: hi in the top 8 bits, lo in the bottom 8. For 0x12 and 0x34 the answer is 0x1234.

    uint8_t hi, lo;
    /* your expression */
    Show a hint

    Shifts bind more loosely than +. What does hi get shifted by?

    2 of 6 tests pass.

    TesthiloExpectedYours
    fail0x120x340x12344,660undefined
    pass0x00x00x000x00
    fail0xFF0xFF0xFFFF65,535undefined
    fail0x800x10x800132,7690x1000065,536
    fail0x00xFF0xFF255undefined
    pass0x10x00x1002560x100256

    Test 1 on your expression. C reads it as hi << (8 + lo).

    gcc -Wall warning: suggest parentheses around ‘+’ inside ‘<<’

    <<undefinedhi18+608lo52

    Undefined: int has 32 bits, so shifting it by 60 is undefined (C11 6.5.7p3).

  3. C3 Average as a fraction. Work out the average sum / count and store it in a float, keeping the fraction: 7 and 2 should give 3.5.

    int sum, count;
    float avg = /* your expression */;
    Show a hint

    When does the division happen, and between which types?

    1 of 5 tests pass.

    TestsumcountExpectedYours
    fail723.5float3.0float
    fail1042.5float2.0float
    fail-72−3.5float−3.0float
    pass933.0float3.0float
    fail130.33333334float0.0float

    Test 1 on your expression. C reads it as (float)(sum / count).

    (float)3.0/3sum7count2
  4. C4 Between 10 and 20. Give 1 when x is strictly between 10 and 20 (11 to 19), and 0 otherwise.

    int x;
    /* your expression */
    Show a hint

    What is 10 < x on its own, and what is that compared with next?

    3 of 8 tests pass.

    TestxExpectedYours
    pass1511
    fail501
    fail2501
    fail1001
    fail2001
    pass1111
    pass1911
    fail-301

    Test 1 on your expression. C reads it as (10 < x) < 20.

    gcc -Wall warning: comparisons like ‘X<=Y<=Z’ do not have their mathematical meaning

    <1<110x1520
  5. C5 Clear bit 3. Give the value of reg with bit 3 (value 0x08) cleared and every other bit unchanged.

    uint32_t reg;
    /* your expression */
    Show a hint

    ~ is a prefix operator. Which does it apply to: 1, or 1 << 3?

    0 of 6 tests pass.

    TestregExpectedYours
    fail0xFF0xF7247undefined
    fail0x80x00undefined
    fail0x00x00undefined
    fail0xFFFFFFFF0xFFFFFFF74,294,967,287undefined
    fail0x70x77undefined
    fail0xF00xF0240undefined

    Test 1 on your expression. C reads it as reg & ((~1) << 3).

    &reg255<<undefined~−213

    Undefined: Shifting a negative value left is undefined (C11 6.5.7p4).

Sources

  • C standard (C11, draft N1570): 6.5p1 to p3 (what an expression is; the grouping comes from the grammar; the order of working out parts is not fixed), 6.5p2 (a variable changed and used without an order is undefined), 6.5.2.4 (postfix ++ gives the old value), 6.5.3 (prefix operators and sizeof, whose operand is not worked out), 6.5.4 (casts), 6.5.5p6 (division rounds toward zero; (a/b)*b + a%b == a), 6.5.7 (shifts), 6.5.8 and 6.5.9 (comparisons give 1 or 0), 6.5.13 and 6.5.14 (&& and || finish the left side first and may skip the right), 6.5.15 (?:), 6.5.16 (assignment), 6.5.17 (comma), 6.3.1.4p1 (floating to integer drops the fraction; undefined if it does not fit), 6.4.4.1 (the type of a number such as 0x80000000).
  • GCC manual, Warning options: -Wparentheses and -Wsequence-point, both turned on by -Wall. Integers implementation: converting to a signed type that is too small keeps the low bits; >> on a negative value copies the sign bit.
  • Checked with GCC 13.3: the expression trees and every value come from a model of these rules that is tested against more than 3,000 random expressions on each of aarch64-linux-gnu-gcc (64-bit ARM) and gcc -m32 (same type sizes as 32-bit ARM), including GCC's exact -Wall warnings, and against 59 expressions with side effects compiled and run on ARM64 (under qemu). The undefined results in the tables are what GCC produced at -O0 and -O2; another compiler may differ.