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 * 4Result: 14 (int)
With brackets
(2 + 3) * 4Result: 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.
| Level | Operators | Example | C reads it as |
|---|---|---|---|
| 1 After a value | a[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 * 4 | 2 + (3 * 4) |
| 4 Add, subtract | +- | a - b - c | (a - b) - c |
| 5 Shifttrap: lower than + and − | <<>> | x << 1 + 1 | x << (1 + 1) |
| 6 Compare | <<=>>= | 3 > 2 > 1 | (3 > 2) > 1 |
| 7 Equal, not equal | ==!= | x & 1 == 0 | x & (1 == 0) |
| 8 Bitwise ANDtrap: lower than == | & | x & 1 == 0 | x & (1 == 0) |
| 9 Bitwise XORtrap: lower than == | ^ | a ^ b == c | a ^ (b == c) |
| 10 Bitwise ORtrap: lower than == | | | a | b == c | a | (b == c) |
| 11 Logical AND | && | a && b || c | (a && b) || c |
| 12 Logical OR | || | a || b && c | a || (b && c) |
| 13 Choosegroups right to left | ? : | a ? b : c ? d : e | a ? b : (c ? d : e) |
| 14 Assigngroups right to left | =+=-=*=&=|=<<=… | a = b = 0 | a = (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 == 0Result: 0 (int)
gcc -Wall warning: suggest parentheses around comparison in operand of ‘&’
With brackets
(x & 1) == 0Result: 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 > 1Result: 0 (int)
gcc -Wall warning: comparisons like ‘X<=Y<=Z’ do not have their mathematical meaning
What maths means
3 > 2 && 2 > 1Result: 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 + 1Result: 12 (int)
gcc -Wall warning: suggest parentheses around ‘+’ inside ‘<<’
With brackets
(x << 1) + 1Result: 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 write | C reads it as | Value | buf afterwards | p 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 / bResult: 3.5 (double)
Cast after dividing
(double)(a / b)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:
| Cast | Result | Why |
|---|---|---|
(int)3.99 | 3 | The fraction is dropped. It does not round to 4. |
(int)-3.99 | −3 | Dropping the fraction moves toward zero, so −3, not −4. |
(uint8_t)300 | 44 | Only the lowest 8 bits are kept: 300 is 1 0010 1100, the low 8 bits are 44. |
(int8_t)200 | −56 | Too big for int8_t. C leaves it to the compiler; GCC keeps the bits, which read as −56. GCC's choice |
(unsigned)-1 | 4,294,967,295 | Converting to unsigned wraps around: −1 becomes the largest unsigned int. |
(uint8_t)a + bwith uint8_t a = 200, b = 100 | 300 | The cast applies to a only. a + b is then worked out as an int. |
(uint8_t)(a + b)with uint8_t a = 200, b = 100 | 44 | Now 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:
| a | b | a / b | a % b | check: (a / b) * b + a % b |
|---|---|---|---|---|
| 7 | 2 | 3 | 1 | 7 |
| −7 | 2 | −3 | −1 | −7 |
| 7 | −2 | −3 | 1 | 7 |
| −7 | −2 | 3 | −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:
| Cast | ARM64 | PC (x86-64) |
|---|---|---|
(uint8_t)300.0 Undefined | 44 | 44 |
(uint8_t)-1.0 Undefined | 0 | 255 |
(int)3e10 Undefined | 2,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.
| Expression | C says | What happens |
|---|---|---|
i = i + 1with int i = 5 | Defined | Gives 6; afterwards i is 6. |
i++ && i++with int i = 5 | Defined | Gives 1; afterwards i is 7. |
(i++, i++)with int i = 5 | Defined | Gives 6; afterwards i is 7. |
i = i++with int i = 5 | Undefined | GCC on ARM64: i stays 5. |
i++ + i++with int i = 5 | Undefined | GCC on ARM64: 11, and i ends at 7. |
i = ++i + 1with int i = 5 | Undefined | GCC on ARM64: i is 7. |
a[i] = i++with int i = 1 | Undefined | GCC on ARM64: stored 1 in a[2], not a[1]. |
printf("%d %d", i, i++)with int i = 5 | Undefined | GCC 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 > 2Result: 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.
int x = 4;
x & 1 == 0How C groups it1 of 4
gcc -Wall warning: suggest parentheses around comparison in operand of ‘&’
Variables
xint4
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 == 0x04How C groups it1 of 4
gcc -Wall warning: suggest parentheses around comparison in operand of ‘&’
Variables
auint8_t200buint8_t100xint7yint2iint5regunsigned int12bufuint8_t[3]10[0]↑ p20[1]30[2]puint8_t *points to buf[0]
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.
How does C group it?
Pick the grouping C uses.
Defined or undefined?
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.
C1 Is bit 2 set?
STATUSis 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.
Test STATUS Expected Yours fail 0x4 1 0 pass 0x5 1 1 fail 0x1 0 1 pass 0x0 0 0 pass 0xFF 1 1 fail 0xFB 0 1 fail 0xC 1 0 Test 1 on your expression. C reads it as
STATUS & (0x04 == 0x04).gcc -Wall warning: suggest parentheses around comparison in operand of ‘&’
C2 Two bytes into one 16-bit value. A sensor sends its reading as two bytes, high byte first. Combine them into one value:
hiin the top 8 bits,loin 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 doeshiget shifted by?2 of 6 tests pass.
Test hi lo Expected Yours fail 0x12 0x34 0x12344,660 undefined pass 0x0 0x0 0x00 0x00 fail 0xFF 0xFF 0xFFFF65,535 undefined fail 0x80 0x1 0x800132,769 0x1000065,536 fail 0x0 0xFF 0xFF255 undefined pass 0x1 0x0 0x100256 0x100256 Test 1 on your expression. C reads it as
hi << (8 + lo).gcc -Wall warning: suggest parentheses around ‘+’ inside ‘<<’
Undefined: int has 32 bits, so shifting it by 60 is undefined (C11 6.5.7p3).
C3 Average as a fraction. Work out the average
sum / countand store it in afloat, 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.
Test sum count Expected Yours fail 7 2 3.5float 3.0float fail 10 4 2.5float 2.0float fail -7 2 −3.5float −3.0float pass 9 3 3.0float 3.0float fail 1 3 0.33333334float 0.0float Test 1 on your expression. C reads it as
(float)(sum / count).C4 Between 10 and 20. Give 1 when
xis strictly between 10 and 20 (11 to 19), and 0 otherwise.int x; /* your expression */Show a hint
What is
10 < xon its own, and what is that compared with next?3 of 8 tests pass.
Test x Expected Yours pass 15 1 1 fail 5 0 1 fail 25 0 1 fail 10 0 1 fail 20 0 1 pass 11 1 1 pass 19 1 1 fail -3 0 1 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
C5 Clear bit 3. Give the value of
regwith 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, or1 << 3?0 of 6 tests pass.
Test reg Expected Yours fail 0xFF 0xF7247 undefined fail 0x8 0x00 undefined fail 0x0 0x00 undefined fail 0xFFFFFFFF 0xFFFFFFF74,294,967,287 undefined fail 0x7 0x77 undefined fail 0xF0 0xF0240 undefined Test 1 on your expression. C reads it as
reg & ((~1) << 3).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 andsizeof, 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 as0x80000000). - GCC manual, Warning options:
-Wparenthesesand-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) andgcc -m32(same type sizes as 32-bit ARM), including GCC's exact-Wallwarnings, 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-O0and-O2; another compiler may differ.