Increment and Decrement Examples: Ring Buffers, String Copy, Ternary, Comma and sizeof-Free Embedded C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

MODULE 5 · LESSON 5.4 · EXAMPLES

Increment and Decrement Examples: Ring Buffers, String Copy, Ternary, Comma and sizeof

Eight worked examples with real output: compound assignment, pre/post increment, a ring buffer, *dst++ = *src++, clamp with the ternary operator, comma in for loops, array length with sizeof and a debounce counter. Study this one of the increment and decrement examples closely.

9
Worked Examples
Intermediate
Level
Real output
Compiled and run

Increment and Decrement Examples: What This Page Covers

These increment and decrement examples put the assignment, ++/–, conditional, comma and sizeof operators of Lesson 5.4 to work in realistic embedded situations. Every program was compiled with GCC and run; the printed output is the real output. These increment and decrement examples build on each other.

#ExampleSkill
1Compound assignment on a register imageop= family
2Pre versus post increment inside expressionsSide effects
3Ring buffer with buf[head++]Post-increment idiom
4Copying with *dst++ = *src++Pointer and ++
5Ternary: clamp, min, max, LED stateConditional operator
6Comma operator in a for loopTwo loop variables
7sizeof for array length and its trapsizeof
8Debounce counter with saturating ++/–Real driver logic
9Mini exercisesSelf-test

Example 1: Compound Assignment on a Register Image

Problem: Apply every compound operator in turn to a control-register image and follow the value. Each op= reads, computes and writes back in one statement. Among the increment and decrement examples this idiom is the most common.

compound_ops.c
#include <stdio.h> #include <stdint.h> int main(void) { uint32_t cr = 0x0000; cr |= (1u << 0); /* enable */ cr |= (1u << 3) | (1u << 5); /* two flags */ printf(“after |= : 0x%04X\n”, (unsigned)cr); cr &= ~(1u << 3); /* clear bit 3 */ printf(“after &=~ : 0x%04X\n”, (unsigned)cr); cr ^= 0x00FF; /* toggle low byte */ printf(“after ^= : 0x%04X\n”, (unsigned)cr); cr <<= 4; /* move up one nibble */ printf(“after <<=4 : 0x%04X\n”, (unsigned)cr); cr >>= 8; printf(“after >>=8 : 0x%04X\n”, (unsigned)cr); cr += 0x10; cr -= 1; cr *= 2; cr /= 3; cr %= 7; printf(“after arithmetic ops: %u\n”, (unsigned)cr); return 0; }
Output (verified by compiling and running)
after |= : 0x0029 after &=~ : 0x0021 after ^= : 0x00DE after <<=4 : 0x0DE0 after >>=8 : 0x000D after arithmetic ops: 4
Trace: After the three |= and &=~ lines the value is 0x0021; XOR with 0xFF gives 0x00DE; shifting left by 4 gives 0x0DE0; shifting right by 8 gives 0x0D. The arithmetic forms then act on 13.

Example 2: Pre versus Post Increment in Expressions

Problem: Show exactly when the update happens. Prefix updates first and yields the new value; postfix yields the old value and updates afterwards. Keep these increment and decrement examples for revision.

pre_post.c
#include <stdio.h> int main(void) { int i = 5, a, b; a = i++; printf(“a = i++ : a=%d i=%d\n”, a, i); i = 5; b = ++i; printf(“b = ++i : b=%d i=%d\n”, b, i); i = 5; int x = i++ + 10; /* uses old i (5), then i becomes 6 */ printf(“i++ + 10 : x=%d i=%d\n”, x, i); i = 5; int y = ++i + 10; printf(“++i + 10 : y=%d i=%d\n”, y, i); int n = 3; while (n–) printf(“loop body n=%d\n”, n); printf(“after loop n=%d\n”, n); return 0; }
Output (verified by compiling and running)
a = i++ : a=5 i=6 b = ++i : b=6 i=6 i++ + 10 : x=15 i=6 ++i + 10 : y=16 i=6 loop body n=2 loop body n=1 loop body n=0 after loop n=-1
i = 5: what the expression yields and what i becomes
ExpressionValue of expressioni afterwards
i++5 (old)6
++i6 (new)6
i--5 (old)4
--i4 (new)4

In while (n--) the test uses the old value, so n = 3 is true and the body sees 2; the loop ends when the old value was 0, leaving n at -1 afterwards.

Example 3: A Ring Buffer with buf[head++]

Problem: A UART receive buffer stores bytes and moves an index. buf[head++] = v; stores at the current index and advances it in one statement; the wrap test follows.

ring_buffer.c
#include <stdio.h> #include <stdint.h> #define RB_SIZE 4 static uint8_t buf[RB_SIZE]; static unsigned head = 0, tail = 0, count = 0; static int put(uint8_t v) { if (count == RB_SIZE) return –1; buf[head++] = v; /* store, then advance */ if (head == RB_SIZE) head = 0; /* wrap */ count++; return 0; } static int get(uint8_t *v) { if (count == 0) return –1; *v = buf[tail++]; if (tail == RB_SIZE) tail = 0; count–; return 0; } int main(void) { uint8_t v; for (uint8_t i = 10; i < 16; i++) printf(“put(%u) -> %d\n”, i, put(i)); while (get(&v) == 0) printf(“get -> %u\n”, v); put(99); put(98); printf(“head=%u tail=%u count=%u\n”, head, tail, count); return 0; }
Output (verified by compiling and running)
put(10) -> 0 put(11) -> 0 put(12) -> 0 put(13) -> 0 put(14) -> -1 put(15) -> -1 get -> 10 get -> 11 get -> 12 get -> 13 head=2 tail=0 count=2
Faster wrap: If the size is a power of two, replace the wrap test with head = (head + 1) & (RB_SIZE - 1); which is branch-free. Mark head and tail volatile when an ISR shares them (Module 14).

Example 4: Copying with *dst++ = *src++

Problem: The classic C string copy. In *dst++ = *src++ the postfix operators bind tighter than *, so the pointer is advanced after each dereference, and the assignment value (the copied char) ends the loop when it is the NUL terminator.

copy_str.c
#include <stdio.h> static char *copy_str(char *dst, const char *src) { char *start = dst; while ((*dst++ = *src++) != ‘\0’) ; /* empty body: copy including the NUL */ return start; } static unsigned my_strlen(const char *s) { const char *p = s; while (*p) p++; return (unsigned)(p – s); } int main(void) { char out[16]; copy_str(out, “STM32F4”); printf(“copied : %s\n”, out); printf(“length : %u\n”, my_strlen(out)); return 0; }
Output (verified by compiling and running)
copied : STM32F4 length : 7
Destination size: This copy has no bound check. Always make sure the destination holds strlen(src) + 1 bytes, or use a length-limited routine.

Example 5: The Conditional Operator: Clamp, Min and LED State

Problem: Limit a PWM duty value to 0–100, choose a status string and compare a macro with a function. The ternary is an expression, so it can sit inside an argument list or an initialiser.

ternary.c
#include <stdio.h> #define MIN(a, b) (((a) < (b)) ? (a) : (b)) static int clamp(int v, int lo, int hi) { return v < lo ? lo : (v > hi ? hi : v); } static int min_fn(int a, int b) { return a < b ? a : b; } int main(void) { int pwm[] = { –20, 0, 55, 100, 140 }; for (int i = 0; i < 5; i++) printf(“clamp(%4d, 0, 100) = %3d\n”, pwm[i], clamp(pwm[i], 0, 100)); int led = 1; printf(“LED is %s\n”, led ? “ON” : “OFF”); int k = 3; int m = MIN(k++, 10); /* argument evaluated twice! */ printf(“macro MIN(k++, 10): m=%d k=%d\n”, m, k); k = 3; m = min_fn(k++, 10); printf(“function min_fn : m=%d k=%d\n”, m, k); return 0; }
Output (verified by compiling and running)
clamp( -20, 0, 100) = 0 clamp( 0, 0, 100) = 0 clamp( 55, 0, 100) = 55 clamp( 100, 0, 100) = 100 clamp( 140, 0, 100) = 100 LED is ON macro MIN(k++, 10): m=4 k=5 function min_fn : m=3 k=4

The macro MIN(k++, 10) evaluates k++ twice (once in the test, once in the result), so k is incremented twice and the wrong value is returned. The function evaluates its argument once. Prefer static inline functions over function-like macros.

Example 6: The Comma Operator in a for Loop

Problem: Reverse an array with two loop variables and see how the comma behaves in an expression. The comma evaluates the left operand, discards it and yields the right one; in a declaration or argument list the comma is only a separator.

comma.c
#include <stdio.h> int main(void) { int a[6] = { 1, 2, 3, 4, 5, 6 }; /* reverse in place: two indices move toward each other */ for (int i = 0, j = 5; i < j; i++, j–) { int t = a[i]; a[i] = a[j]; a[j] = t; } for (int k = 0; k < 6; k++) printf(“%d “, a[k]); printf(“\n”); int x = (printf(“side effect\n”), 42); /* value of the last operand */ printf(“x = %d\n”, x); int y, z; y = 1, 2; /* = binds tighter than the comma */ z = (1, 2); printf(“y=%d z=%d\n”, y, z); return 0; }
Output (verified by compiling and running)
6 5 4 3 2 1 side effect x = 42 y=1 z=2
Gotcha: y = 1, 2; parses as (y = 1), 2;, so y is 1. Only the parenthesised form gives 2.

Example 7: sizeof for Array Length and Its Trap

Problem: Compute the number of elements of an array without a magic number, then see why the same expression fails inside a function.

sizeof_count.c
#include <stdio.h> #include <stdint.h> #define COUNT_OF(a) (sizeof(a) / sizeof((a)[0])) static const uint16_t table[] = { 100, 200, 300, 400, 500 }; static unsigned wrong(uint16_t arr[]) /* arr is really a pointer here */ { return (unsigned)(sizeof(arr) / sizeof(arr[0])); } int main(void) { uint16_t samples[8]; printf(“sizeof samples = %zu bytes\n”, sizeof samples); printf(“COUNT_OF(samples) = %zu elements\n”, COUNT_OF(samples)); printf(“COUNT_OF(table) = %zu elements\n”, COUNT_OF(table)); printf(“wrong(samples) = %u (pointer is %zu bytes on this PC)\n”, wrong(samples), sizeof(uint16_t *)); return 0; }
Output (verified by compiling and running)
sizeof samples = 16 bytes COUNT_OF(samples) = 8 elements COUNT_OF(table) = 5 elements wrong(samples) = 4 (pointer is 8 bytes on this PC)
Pointer size is platform-specific: On the 64-bit PC used here a pointer is 8 bytes, so the wrong answer is 4; on the 32-bit Cortex-M4 a pointer is 4 bytes and the wrong answer would be 2. The lesson is the same: pass the length as a separate parameter.

Example 8: A Debounce Counter with Saturating ++ and —

Problem: A mechanical button bounces. Count up on pressed samples and down on released ones, saturating at 0 and 4. The output changes only when the counter reaches an end, which filters short glitches.

debounce.c
#include <stdio.h> #define DEBOUNCE_MAX 4 int main(void) { int raw[] = { 0,1,1,0,1,1,1,1,1,0,0,0,0,0,0 }; /* noisy button samples */ int n = (int)(sizeof raw / sizeof raw[0]); int cnt = 0, state = 0; for (int i = 0; i < n; i++) { raw[i] ? (cnt < DEBOUNCE_MAX ? cnt++ : 0) : (cnt > 0 ? cnt– : 0); if (cnt == DEBOUNCE_MAX) state = 1; else if (cnt == 0) state = 0; printf(“sample %2d raw=%d counter=%d stable=%d\n”, i, raw[i], cnt, state); } return 0; }
Output (verified by compiling and running)
sample 0 raw=0 counter=0 stable=0 sample 1 raw=1 counter=1 stable=0 sample 2 raw=1 counter=2 stable=0 sample 3 raw=0 counter=1 stable=0 sample 4 raw=1 counter=2 stable=0 sample 5 raw=1 counter=3 stable=0 sample 6 raw=1 counter=4 stable=1 sample 7 raw=1 counter=4 stable=1 sample 8 raw=1 counter=4 stable=1 sample 9 raw=0 counter=3 stable=1 sample 10 raw=0 counter=2 stable=1 sample 11 raw=0 counter=1 stable=1 sample 12 raw=0 counter=0 stable=0 sample 13 raw=0 counter=0 stable=0 sample 14 raw=0 counter=0 stable=0

The ternaries keep the counter within range without separate if statements. On the STM32F407 the sample would come from (GPIOA->IDR >> 0) & 1u called from a 1 ms timer tick.

Example 9: Mini Exercises

Exercise 1: With i = 3, what are i++ * 2 and then i?
6 and i = 4.
Exercise 2: With i = 3, what is ++i * 2?
8, and i = 4.
Exercise 3: Rewrite if (a > b) m = a; else m = b; as one statement.
m = (a > b) ? a : b;
Exercise 4: What does x = (1, 2, 3); store?
3, the last operand.
Exercise 5: What is sizeof(int[10]) on the STM32F407?
40 bytes (10 × 4).
Exercise 6: Why is a[i] = i++; a bug?
The object i is read and modified without a sequence point between them: undefined behavior.
Exercise 7: Which operator has the lowest precedence of all?
The comma operator.

Key Takeaways from the Increment and Decrement Examples

  • These increment and decrement examples show that prefix yields the new value and postfix yields the old one.
  • buf[head++] = v; and *dst++ = *src++ are standard idioms; know the precedence that makes them work.
  • Compound assignment evaluates the left side once and keeps the code short.
  • The ternary is an expression: ideal for clamps and small selections, but a macro version double-evaluates arguments.
  • The comma operator belongs mainly in for headers.
  • Use sizeof a / sizeof a[0] only on real arrays, never on function parameters.

Ready for the quiz?

Next: predict the output of tricky ++/– expressions, spot the undefined behavior and answer the interview questions.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

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

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →