|
20 | 20 |
|
21 | 21 | ## 🎯 **Overview** |
22 | 22 |
|
| 23 | +### Concept: Tell the compiler the truth about how data changes |
| 24 | + |
| 25 | +Think of qualifiers as contracts: |
| 26 | +- `const`: intent is read-only at this access point |
| 27 | +- `volatile`: value may change outside the compiler’s view (hardware/ISR) |
| 28 | +- `restrict`: this pointer is the only way to access the referenced object |
| 29 | + |
| 30 | +### Why it matters in embedded |
| 31 | +- Correct `volatile` prevents the compiler from caching HW register values. |
| 32 | +- `const` enables placement in ROM and better optimization. |
| 33 | +- `restrict` allows the compiler to vectorize/memcpy efficiently in hot paths. |
| 34 | + |
| 35 | +### Minimal examples |
| 36 | +```c |
| 37 | +// Read-only lookup table likely in Flash |
| 38 | +static const uint16_t lut[] = {1,2,3,4}; |
| 39 | + |
| 40 | +// Memory-mapped I/O register |
| 41 | +#define GPIOA_ODR (*(volatile uint32_t*)0x40020014u) |
| 42 | + |
| 43 | +// Non-aliasing buffers (improves copy performance) |
| 44 | +void copy_fast(uint8_t * restrict dst, const uint8_t * restrict src, size_t n); |
| 45 | +``` |
| 46 | +
|
| 47 | +### Try it |
| 48 | +1. Remove `volatile` from a polled status register read and compile with `-O2`; inspect assembly to see hoisted loads. |
| 49 | +2. Add/Remove `restrict` on a memset/memcpy-like loop and measure on target. |
| 50 | +
|
| 51 | +### Takeaways |
| 52 | +- `volatile` is about visibility, not atomicity or ordering. |
| 53 | +- `const` expresses intent and may change placement; don’t cast it away to write. |
| 54 | +- Use `restrict` only when you can prove no aliasing. |
| 55 | +
|
| 56 | +> Platform note: For I/O ordering on some MCUs/SoCs, pair volatile accesses with memory barriers when required by the architecture. |
| 57 | +
|
23 | 58 | Type qualifiers in C provide important hints to the compiler about how variables should be treated: |
24 | 59 | - **const** - Indicates read-only data |
25 | 60 | - **volatile** - Indicates data that can change unexpectedly |
|
0 commit comments