r/cprogramming • • Jul 31 '26

After one week learning C

Yeah, my anxiety is hitting pretty hard right now... lol.

0 Upvotes

17 comments sorted by

View all comments

Show parent comment

2

u/nerd5code Aug 01 '26

uint8 status = *(0xC000); isn't a binding syntax I've ever seen, first of all; closest is … @ 0xC000 or __attribute__((at(0xC000))) or various pragmata. In some cases the compiler will be packaged with a linker script or assembly-language/C header that declares register names, so you can refer to them naturally through those mechanisms. Often in inline assembly you can do regname = 0xC000 or .equ/.set regname, 0xC000, in which case you's just declare an extern variable for it in C.

Second, this is flatly invalid in ISO C, unless at block scope (in which case, you're just dereferencing an integer, which only works in Elder C) and you're using a C≥99 language mode (i.e., not Elder C) or eqv. compiler extension. It says you want the variable status to name a uint8 storage space, and it should be initialized to the dereference of address 0xC000.

Third, even if we assume binding, it's not volatile, so the compiler can assume its value doesn't change from load to load, without some compiler-visible intervening store. Similarly, the compiler can defer, elide, or merge loads and stores, which may break the hardware.

If you want to do it portably without using binding syntax etc., there are two reasonably reasonable options, but either way first you'd

#define REGADDX_STATUS 0xC000U

with trailing U so 16-bit int doesn't overflow or sign-extend unexpectedly. For the easiest approach,

#define reg_status (*(const/*?*/ volatile uint8 *)REGADDX_STATUS))

reg_status now works like a variable. (Include const only if read-only, ofc.) Alternatively,

/* File scope: */
const volatile uint8 *const reg_status = (uint8 *)REGADDX_STATUS;

This requires you to explicitly dereference with *reg_status if you want to access it, but assuming C≥89 preprocessor,

#define reg_status (*reg_status)

will avoid that.

I note that both of these approaches require integer-pointer conversion (as does yours), which is implementation-specified behavior that won't always work as expected. However, just about every mainstream ABI (I can think of like two exceptions in total, namely CHERI and OS/400's older P128 ABI, and those aren't mainstream) will follow the nonnormative recommendation that the integer side of the conversion is basically a pun, of the sort you'd get in C≥99 from

union {uintptr_t address; const volatile void *ptr;} u;
u.address = 0xC000;
reg_status = u.ptr;

—and this is especially true of embedded compilers.