Theory- Assignment Operators in Embedded C: Compound Assignment, ++/–, Ternary, Comma and sizeof-Free Embedded C Course in Hyderabad

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

MODULE 5 · LESSON 5.4 · THEORY

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.

55 min
Read Time
Beginner → Intermediate
Level
M5 · L4
Module / Lesson

What You Will Learn

✓ The simple assignment operator and why it is an expression
✓ All compound assignment operators and what they hide
✓ Prefix and postfix increment/decrement: the value versus the side effect
✓ Why i = i++ + ++i is undefined and what GCC says
✓ The conditional (ternary) operator ?:, its result type and safe uses
✓ The comma operator and where commas are not operators
✓ sizeof as a compile-time operator, and the array-parameter trap
✓ The full precedence table for the whole module

Key Terms

AssignmentlvaluervalueCompound assignmentPrefixPostfixSide effectSequence pointTernaryConditional operatorComma operatorsizeofsize_tPrecedenceAssociativity

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.

assign_basic.c
#include <stdio.h> int main(void) { int a, b, c; a = 5; /* store 5 in a */ b = a + 3; /* right side is evaluated first */ c = b = a = 7; /* chained: associates right to left */ printf(“a=%d b=%d c=%d\n”, a, b, c); int x; printf(“value of (x = 9) is %d\n”, (x = 9)); /* assignment yields the stored value */ int n; while ((n = 3) > 5) { } /* assign and test in one expression */ printf(“n=%d\n”, n); return 0; }
Output (verified by compiling and running)
a=7 b=7 c=7 value of (x = 9) is 9 n=3
TermMeaningExample
lvaluehas a memory location; can be on the left of =x, buf[3], *p, TIM2->CNT
rvaluea value only; right side5, a + b, f()
Initializationthe first value given in the declaration; not an assignmentint x = 5;
Assignmentreplaces the value of an existing objectx = 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.

assign_convert.c
#include <stdio.h> #include <stdint.h> int main(void) { uint8_t small; int big = 300; small = big; /* 300 does not fit: stored modulo 256 */ printf(“uint8_t small = 300 -> %u\n”, small); int i; i = 3.99; /* the fraction is discarded */ printf(“int i = 3.99 -> %d\n”, i); float f; f = 16777217; /* 2^24 + 1 is not representable */ printf(“float f = 16777217 -> %.1f\n”, f); unsigned u = –1; printf(“unsigned u = -1 -> %u\n”, u); return 0; }
Output (verified by compiling and running)
uint8_t small = 300 -> 44 int i = 3.99 -> 3 float f = 16777217 -> 16777216.0 unsigned u = -1 -> 4294967295
= versus ==: The most common typo in C is 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.

OperatorEquivalent toTypical use in firmware
+=a = a + baccumulate, advance a pointer or counter by n
-=a = a - bdecrement a timeout, bytes remaining
*=a = a * bscale a value
/=a = a / bdivide a value
%=a = a % bwrap an index
&=a = a & bclear bits (with ~mask), apply a mask
|=a = a | bset bits
^=a = a ^ btoggle bits, checksum
<<=a = a << bshift left
>>=a = a >> bshift right
compound.c
#include <stdio.h> #include <stdint.h> int main(void) { int x = 10; x += 5; printf(“x += 5 -> %d\n”, x); x -= 3; printf(“x -= 3 -> %d\n”, x); x *= 2; printf(“x *= 2 -> %d\n”, x); x /= 4; printf(“x /= 4 -> %d\n”, x); x %= 4; printf(“x %%= 4 -> %d\n”, x); uint8_t r = 0x0F; r <<= 2; printf(“r <<= 2 -> 0x%02X\n”, r); r >>= 1; printf(“r >>= 1 -> 0x%02X\n”, r); r &= 0x3C; printf(“r &= 0x3C -> 0x%02X\n”, r); r |= 0x81; printf(“r |= 0x81 -> 0x%02X\n”, r); r ^= 0xFF; printf(“r ^= 0xFF -> 0x%02X\n”, r); int a[3] = { 1, 2, 3 }, i = 0; a[i++] += 10; /* i++ is evaluated once, so a[0] is the target */ printf(“a = %d %d %d, i = %d\n”, a[0], a[1], a[2], i); int y = 5; y *= 2 + 3; /* y = y * (2 + 3), not (y * 2) + 3 */ printf(“y *= 2 + 3 -> %d\n”, y); return 0; }
Output (verified by compiling and running)
x += 5 -> 15 x -= 3 -> 12 x *= 2 -> 24 x /= 4 -> 6 x %= 4 -> 2 r <<= 2 -> 0x3C r >>= 1 -> 0x1E r &= 0x3C -> 0x1C r |= 0x81 -> 0x9D r ^= 0xFF -> 0x62 a = 11 2 3, i = 1 y *= 2 + 3 -> 25
The right side is evaluated first, completely: 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:

FormNameStepsValue of the expression
++xprefix incrementadd 1, then use the valuethe new value
x++postfix incrementuse the value, then add 1the old value
--xprefix decrementsubtract 1, then usethe new value
x--postfix decrementuse, then subtract 1the old value
inc_dec.c
#include <stdio.h> int main(void) { int x = 5, y; y = x++; /* y gets the OLD value, then x becomes 6 */ printf(“y = x++ -> y=%d x=%d\n”, y, x); y = ++x; /* x becomes 7 first, y gets the NEW value */ printf(“y = ++x -> y=%d x=%d\n”, y, x); y = x–; /* y=7, then x=6 */ printf(“y = x– -> y=%d x=%d\n”, y, x); y = –x; /* x=5, then y=5 */ printf(“y = –x -> y=%d x=%d\n”, y, x); int i = 0; int arr[4] = { 10, 20, 30, 40 }; printf(“arr[i++] reads %d then i=%d\n”, arr[i++], i); /* i++ and the read of i: avoid this style */ return 0; }
Output (verified by compiling and running)
y = x++ -> y=5 x=6 y = ++x -> y=7 x=7 y = x– -> y=7 x=6 y = –x -> y=5 x=5 arr[i++] reads 10 then i=1
x = 5: what each form returns and leaves behind
y = x++
expression = 5
x afterwards = 6
y = ++x
expression = 6
x afterwards = 6
y = x–
expression = 5
x afterwards = 4
y = –x
expression = 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 ++i are 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.
On a volatile register, x++ is a full read-modify-write: 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.

seq.c
#include <stdio.h> int main(void) { int i = 1; i = i++ + ++i; /* modifies i twice with no sequence point */ int a[3] = { 0 }; int j = 0; a[j] = j++; /* is j read before or after the increment? */ printf(“%d %d\n”, i, a[0]); return 0; }
Real GCC warnings for expressions that break the rule
seq.c: In function ‘main’: seq.c:6:7: warning: operation on ‘i’ may be undefined [-Wsequence-point] 6 | i = i++ + ++i; /* modifies i twice with no sequence point */ | ~~^~~~~~~~~~~ seq.c:6:7: warning: operation on ‘i’ may be undefined [-Wsequence-point] seq.c:9:13: warning: operation on ‘j’ may be undefined [-Wsequence-point] 9 | a[j] = j++; /* is j read before or after the increment? */ | ~^~
ExpressionProblemRewrite
i = i++ + ++i;i modified three timesseparate statements
a[i] = i++;unspecified which i is useda[i] = i; i++;
f(i++, i++)argument evaluation order unspecifiedevaluate into temporaries first
x = x++;modifies x twicex++;

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.

ternary_basic.c
#include <stdio.h> #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define CLAMP(x, lo, hi) ((x) < (lo) ? (lo) : ((x) > (hi) ? (hi) : (x))) int main(void) { int temp = 42; const char *state = (temp > 40) ? “overheat” : “normal”; printf(“state: %s\n”, state); int a = 7, b = 12; printf(“max(%d,%d) = %d\n”, a, b, MAX(a, b)); int raw[] = { –50, 0, 500, 1023, 5000 }; for (int i = 0; i < 5; i++) printf(“clamp(%5d, 0, 1023) = %4d\n”, raw[i], CLAMP(raw[i], 0, 1023)); printf(“parity of %d: %s\n”, 7, (7 & 1) ? “odd” : “even”); printf(“LED request: %s\n”, 0 ? “ON” : “OFF”); return 0; }
Output (verified by compiling and running)
state: overheat max(7,12) = 12 clamp( -50, 0, 1023) = 0 clamp( 0, 0, 1023) = 0 clamp( 500, 0, 1023) = 500 clamp( 1023, 0, 1023) = 1023 clamp( 5000, 0, 1023) = 1023 parity of 7: odd LED request: OFF
How cond ? a : b chooses
cond
→
non-zero (true): value is a, b is not evaluated
zero (false): value is b, a is not evaluated

Rules and traps

  • Result type: if a and b have different arithmetic types, the usual conversions apply: c ? 1 : 2.5 is always a double, 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 : e reads as a ? b : (c ? d : e). Chains of more than one level are unreadable; use if / else if.
  • Macro double evaluation: MAX(i++, j) expands to ((i++) > (j) ? (i++) : (j)): i may be incremented twice. Use static inline functions for min/max in new code.
ternary_traps.c
#include <stdio.h> #define MAX(a, b) ((a) > (b) ? (a) : (b)) int main(void) { int c = 1; printf(“sizeof(c ? 1 : 2.5) = %zu (a double, because of the 2.5)\n”, sizeof(c ? 1 : 2.5)); printf(“value of (c ? 1 : 2.5) = %.1f\n”, c ? 1 : 2.5); int i = 5, j = 3; int m = MAX(i++, j); /* i++ evaluated twice */ printf(“MAX(i++, j) -> m=%d, i=%d (i was incremented twice)\n”, m, i); int x = 0, y = 0; int r = 1 ? (x = 10) : (y = 20); /* only one branch runs */ printf(“r=%d x=%d y=%d\n”, r, x, y); return 0; }
Output (verified by compiling and running)
sizeof(c ? 1 : 2.5) = 8 (a double, because of the 2.5) value of (c ? 1 : 2.5) = 1.0 MAX(i++, j) -> m=6, i=7 (i was incremented twice) r=10 x=10 y=0

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.

comma_op.c
#include <stdio.h> int main(void) { int a, b; a = (1, 2, 3); /* evaluates 1, then 2, then 3: a gets 3 */ printf(“a = (1, 2, 3) -> %d\n”, a); b = 1, 2, 3; /* parsed as (b = 1), 2, 3 : b gets 1 */ printf(“b = 1, 2, 3 -> %d\n”, b); for (int i = 0, j = 10; i < j; i += 3, j -= 3) /* commas in the init and update parts */ printf(“i=%d j=%d\n”, i, j); int x = 0, y = 0; x = (y = 4, y * 2); /* assign y, then use it */ printf(“x=%d y=%d\n”, x, y); return 0; }
Output (verified by compiling and running)
a = (1, 2, 3) -> 3 b = 1, 2, 3 -> 1 i=0 j=10 i=3 j=7 x=8 y=4
ContextComma is…Example
Declaration listseparator (not the operator)int a, b, c;
Function argumentsseparatorf(a, b)
Initializer listseparator{ 1, 2, 3 }
for init/updateoperatori++, j--
Inside parentheses in an expressionoperator(x = 1, y = 2)
Style: The comma operator is legitimate in 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.

sizeof_demo.c
#include <stdio.h> #include <stdint.h> typedef struct { uint8_t id; uint32_t value; } Sample; int main(void) { int table[10]; int i = 5; printf(“sizeof(char)=%zu short=%zu int=%zu long=%zu long long=%zu double=%zu\n”, sizeof(char), sizeof(short), sizeof(int), sizeof(long), sizeof(long long), sizeof(double)); printf(“sizeof(table) = %zu bytes\n”, sizeof(table)); printf(“elements in table = %zu\n”, sizeof(table) / sizeof(table[0])); printf(“sizeof(Sample) = %zu (padding included)\n”, sizeof(Sample)); printf(“sizeof(i++) = %zu, i is still %d\n”, sizeof(i++), i); printf(“sizeof \”ARM\” = %zu (3 chars + NUL)\n”, sizeof “ARM”); return 0; }
Output (verified by compiling and running)
sizeof(char)=1 short=2 int=4 long=8 long long=8 double=8 sizeof(table) = 40 bytes elements in table = 10 sizeof(Sample) = 8 (padding included) sizeof(i++) = 4, i is still 5 sizeof “ARM” = 4 (3 chars + NUL)

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:

sizeof_trap.c
#include <stdio.h> #include <stdint.h> static void by_param(int values[10]) /* looks like an array, is really int * */ { printf(“inside the function : sizeof(values) = %zu (a pointer), %zu \”elements\”\n”, sizeof(values), sizeof(values) / sizeof(values[0])); } int main(void) { int data[10]; printf(“in the caller : sizeof(data) = %zu -> %zu elements\n”, sizeof(data), sizeof(data) / sizeof(data[0])); by_param(data); return 0; }
Output (verified by compiling and running)
in the caller : sizeof(data) = 40 -> 10 elements inside the function : sizeof(values) = 8 (a pointer), 2 “elements”
Always pass the length: A function that receives an array must also receive its element count: 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.

LevelOperatorsAssociativity
1postfix ++ --, (), [], ., ->left to right
2prefix ++ --, unary + - ! ~, * (dereference), & (address), sizeof, castsright 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
precedence_final.c
#include <stdio.h> int main(void) { int a = 5, b = 2, c = 0; c = a > b ? a – b : b – a; /* ?: above =, below > and – */ printf(“c = a > b ? a-b : b-a -> %d\n”, c); int x = 3; int y = x++ * 2; /* postfix binds before *: uses 3 */ printf(“y = x++ * 2 -> y=%d x=%d\n”, y, x); int z = -x++; /* unary minus and ++ associate right to left */ printf(“z = -x++ -> z=%d x=%d\n”, z, x); int p = 1, q = 0; int r = p || q && 0; /* && before || */ printf(“r = p || q && 0 -> %d\n”, r); int s = 8; s >>= 1 + 1; /* RHS evaluated first: s >>= 2 */ printf(“s >>= 1 + 1 -> %d\n”, s); return 0; }
Output (verified by compiling and running)
c = a > b ? a-b : b-a -> 3 y = x++ * 2 -> y=6 x=4 z = -x++ -> z=-4 x=5 r = p || q && 0 -> 1 s >>= 1 + 1 -> 2
Practical rule again: If you need to look up the table to know how an expression parses, add parentheses. Readers of your code should not need the table either.

9. Common Mistakes

Mistake 1 — = instead of == in a condition: Always true or always false depending on the assigned value. Use -Wall.
Mistake 2 — modifying and using the same variable in one expression: a[i] = i++;, i = i++ + 1; are undefined.
Mistake 3 — thinking postfix and prefix differ in a statement of their own: i++; and ++i; behave identically there; the difference only shows when the value is used.
Mistake 4 — non-atomic ++ on shared volatile data: It is a read-modify-write and can lose updates between an ISR and main.
Mistake 5 — MAX/MIN macros with side effects: MAX(i++, j) evaluates its argument twice.
Mistake 6 — nested ternary chains: Hard to read and easy to get wrong; use if / else if.
Mistake 7 — sizeof on a function parameter array: You get the pointer size (4 on a Cortex-M4), not the array size.
Mistake 8 — ignoring the destination width on assignment: 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 ++i as a separate statement; do not mix with other uses of i.
  • 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 inline functions instead of function-like macros that evaluate arguments more than once.
  • Compile with -Wall -Wextra -Wconversion and 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, ++x the new; both leave x incremented.
  • Modifying an object twice (or using it and modifying it) in one expression is undefined behavior.
  • cond ? a : b evaluates only one branch; its type follows the usual arithmetic conversions.
  • The comma operator sequences expressions; commas in declarations and arguments are separators.
  • sizeof is a compile-time operator returning size_t; on an array parameter it measures a pointer.
  • Precedence order ends with assignment and the comma operator at the bottom.

Frequently Asked Questions

What is the difference between ++i and i++?
Both add 1 to i. ++i returns the new value, i++ returns the old value. As a standalone statement they are identical; the difference matters only when the expression result is used.
Why is i = i++ + ++i undefined?
It modifies i more than once between two sequence points, so the standard places no requirement on the result. Different compilers or optimization levels may give different values.
How does the ternary operator work?
c ? a : b evaluates c; if non-zero the result is a, otherwise b. Only the selected operand is evaluated, and the result type follows the usual arithmetic conversions of a and b.
What does the comma operator do?
It evaluates the left operand, discards it, evaluates the right operand and yields its value. It appears mainly in for-loop headers such as for (i = 0, j = n; i < j; i++, j--).
Is sizeof a function?
No, it is an operator evaluated at compile time. It does not evaluate its operand (apart from variable-length arrays) and returns a value of type size_t.
Is x++ atomic on a Cortex-M4?
No. It compiles to load, add, store. An interrupt between them can modify the variable, so shared counters need a critical section, exclusive load/store or atomics.

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

Leave a Reply

Your email address will not be published. Required fields are marked *