Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
Assignment Operators in Embedded C: Compound Assignment, ++/–, Ternary, Comma and sizeof
Assignment as an expression, all compound operators, prefix versus postfix increment, undefined expressions and GCC warnings, the conditional operator, the comma operator, sizeof and the complete precedence table. Keep this in mind whenever you apply assignment operators in embedded C.
What You Will Learn
i = i++ + ++i is undefined and what GCC says?:, its result type and safe usessizeof as a compile-time operator, and the array-parameter trapKey Terms
1. Simple Assignment
The assignment operator = stores the value of its right operand into the object named by its left operand. The left side must be a modifiable lvalue, an expression that designates a memory location (a variable, an array element, *p, a register such as GPIOD->ODR). The right side can be any expression. Understanding the assignment operators in embedded C starts with one surprising fact: assignment is itself an expression that has a value, namely the value just stored. Many subtle bugs with assignment operators in embedded C start here.
| Term | Meaning | Example |
|---|---|---|
| lvalue | has a memory location; can be on the left of = | x, buf[3], *p, TIM2->CNT |
| rvalue | a value only; right side | 5, a + b, f() |
| Initialization | the first value given in the declaration; not an assignment | int x = 5; |
| Assignment | replaces the value of an existing object | x = 6; |
Conversion on assignment
The right-hand value is converted to the type of the left-hand object. When the destination is narrower, high bits are lost silently (Lesson 3.3): This is the core rule behind assignment operators in embedded C.
if (x = 5). It assigns 5 to x and the condition is always true. Compile with -Wall (GCC warns: suggest parentheses around assignment used as truth value). If you really want an assignment in a condition, write the extra parentheses and the comparison explicitly: if ((n = read()) != 0).2. Compound Assignment Operators
Each arithmetic or bitwise binary operator has a compound form: a op= b is equivalent to a = a op b, except that a is evaluated only once. That detail matters for expressions with side effects, such as buf[i++] += 2, and for volatile registers, where it guarantees one read and one write. Reviewers check assignment operators in embedded C closely in ISR code.
| Operator | Equivalent to | Typical use in firmware |
|---|---|---|
+= | a = a + b | accumulate, advance a pointer or counter by n |
-= | a = a - b | decrement a timeout, bytes remaining |
*= | a = a * b | scale a value |
/= | a = a / b | divide a value |
%= | a = a % b | wrap an index |
&= | a = a & b | clear bits (with ~mask), apply a mask |
|= | a = a | b | set bits |
^= | a = a ^ b | toggle bits, checksum |
<<= | a = a << b | shift left |
>>= | a = a >> b | shift right |
y *= 2 + 3 means y = y * (2 + 3). Beginners often read it as y = y * 2 + 3.Compound assignment also performs the usual arithmetic conversions, which can hide a truncation. In uint8_t c = 200; c += 100; the addition is done in int (300) and the result is stored modulo 256 (44). Interviewers test assignment operators in embedded C on exactly this point.
3. Increment and Decrement: ++ and —
++ adds 1 to an object and -- subtracts 1. Each comes in two forms that differ in the value of the expression, not in the final value of the variable:
| Form | Name | Steps | Value of the expression |
|---|---|---|---|
++x | prefix increment | add 1, then use the value | the new value |
x++ | postfix increment | use the value, then add 1 | the old value |
--x | prefix decrement | subtract 1, then use | the new value |
x-- | postfix decrement | use, then subtract 1 | the old value |
x afterwards = 6
x afterwards = 6
x afterwards = 4
x afterwards = 4
Where ++ and — are used in embedded code
- Loop counters:
for (i = 0; i < n; i++). For a standalone statement,i++and++iare identical. - Buffer fill:
buf[head++] = byte;stores at the current index, then advances it. - Pointer walking:
*dst++ = *src++;copies one element and advances both pointers (Module 9). - Event counters:
g_overflows++;inside an ISR.
TIM2->CNT++ reads the counter, adds 1 and writes it back. If the hardware changes the register in between, the update is lost. The same applies to a shared volatile counter modified in an ISR and in main(): count++ is not atomic.4. Side Effects, Sequence Points and Undefined Expressions
An expression with ++ or an assignment has a side effect: it changes an object. The C standard says that between two sequence points an object may be modified at most once, and its prior value may be read only to compute the new value. Break that rule and the behavior is undefined: different compilers, optimization levels and even different versions give different answers.
| Expression | Problem | Rewrite |
|---|---|---|
i = i++ + ++i; | i modified three times | separate statements |
a[i] = i++; | unspecified which i is used | a[i] = i; i++; |
f(i++, i++) | argument evaluation order unspecified | evaluate into temporaries first |
x = x++; | modifies x twice | x++; |
Sequence points occur at the end of a full expression (the ;), after the first operand of &&, ||, ?: and the comma operator, and before a function is called. The practical rule is simple: never use an object twice in one expression if you also modify it there.
5. The Conditional (Ternary) Operator ?:
The conditional operator is C’s only ternary operator. cond ? a : b evaluates cond; if it is non-zero the value of the whole expression is a, otherwise b. Only the chosen branch is evaluated. It is an expression, so it can sit inside another expression, an initializer or a function argument, which an if statement cannot do.
Rules and traps
- Result type: if
aandbhave different arithmetic types, the usual conversions apply:c ? 1 : 2.5is always adouble, even when 1 is chosen. - Precedence:
?:is very low (above assignment, below||). Parenthesise the whole conditional when you use it in a larger expression:"x=" + (c ? 1 : 2). - Associativity: right to left, so
a ? b : c ? d : ereads asa ? b : (c ? d : e). Chains of more than one level are unreadable; useif / else if. - Macro double evaluation:
MAX(i++, j)expands to((i++) > (j) ? (i++) : (j)):imay be incremented twice. Usestatic inlinefunctions for min/max in new code.
6. The Comma Operator
The comma operator evaluates its left operand, discards the result, and then evaluates its right operand, whose value becomes the value of the whole expression. There is a sequence point between the two, so the order is guaranteed. It has the lowest precedence of all operators.
| Context | Comma is… | Example |
|---|---|---|
| Declaration list | separator (not the operator) | int a, b, c; |
| Function arguments | separator | f(a, b) |
| Initializer list | separator | { 1, 2, 3 } |
for init/update | operator | i++, j-- |
| Inside parentheses in an expression | operator | (x = 1, y = 2) |
for headers with two counters and in macros that must be one expression. Elsewhere it hurts readability, and MISRA C forbids it.7. sizeof: A Compile-Time Operator
sizeof is an operator, not a function, and it is evaluated by the compiler: it yields the size in bytes of a type or of the type of an expression, as a value of type size_t (an unsigned type, print it with %zu). The operand of sizeof is not evaluated, so sizeof(i++) does not increment i.
The sizes of long and long long above are for the PC used to build this page; on the STM32F407 with arm-none-eabi-gcc they are 4 and 8 bytes. char is always 1, short 2, int 4, pointers 4. Use <stdint.h> types when the exact width matters.
The array-parameter trap
sizeof(array) / sizeof(array[0]) counts the elements of an array only where the compiler still sees the array. When an array is passed to a function it decays to a pointer, and sizeof then measures the pointer:
void process(const int *values, size_t n). Define a macro #define ARRAY_LEN(a) (sizeof(a) / sizeof((a)[0])) and use it only on real arrays. Recent GCC warns about the trap with -Wsizeof-array-argument (enabled by -Wall).8. Operator Precedence and Associativity: The Complete Table
Together with Lessons 5.1 to 5.3 you have now met every operator in the table. Memorise the groups, not the numbers.
| Level | Operators | Associativity |
|---|---|---|
| 1 | postfix ++ --, (), [], ., -> | left to right |
| 2 | prefix ++ --, unary + - ! ~, * (dereference), & (address), sizeof, casts | right to left |
| 3 | * / % | left to right |
| 4 | + - | left to right |
| 5 | << >> | left to right |
| 6 | < <= > >= | left to right |
| 7 | == != | left to right |
| 8 | & | left to right |
| 9 | ^ | left to right |
| 10 | | | left to right |
| 11 | && | left to right |
| 12 | || | left to right |
| 13 | ?: | right to left |
| 14 | = += -= *= /= %= &= ^= |= <<= >>= | right to left |
| 15 | , | left to right |
9. Common Mistakes
-Wall.a[i] = i++;, i = i++ + 1; are undefined.i++; and ++i; behave identically there; the difference only shows when the value is used.MAX(i++, j) evaluates its argument twice.uint8_t x = big_value; truncates silently; compile with -Wconversion to see these.10. Best Practices for Assignment Operators in Embedded C
- Initialize at declaration; assign later only when the value changes.
- Do one assignment or one increment per statement unless the idiom is standard (
*dst++ = *src++). - Prefer
i++or++ias a separate statement; do not mix with other uses ofi. - Use compound operators on registers (
|=,&=) to get a single evaluation of the address. - Guard shared counters with a critical section or use hardware atomic support.
- Keep ternaries short and parenthesised; at most one level of nesting, preferably none.
- Use
static inlinefunctions instead of function-like macros that evaluate arguments more than once. - Compile with
-Wall -Wextra -Wconversionand fix every warning about assignments in conditions and narrowing.
Key Takeaways — Lesson 5.4
- The assignment operators in embedded C store a converted value into an lvalue and yield the stored value; chains associate right to left.
- Compound operators evaluate the left operand once: one register read and one write.
x++yields the old value,++xthe new; both leave x incremented.- Modifying an object twice (or using it and modifying it) in one expression is undefined behavior.
cond ? a : bevaluates only one branch; its type follows the usual arithmetic conversions.- The comma operator sequences expressions; commas in declarations and arguments are separators.
sizeofis a compile-time operator returningsize_t; on an array parameter it measures a pointer.- Precedence order ends with assignment and the comma operator at the bottom.
Frequently Asked Questions
Ready to practise?
Next: compound assignment with bitwise operators, pre versus post increment in expressions and the ternary operator in embedded code.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments