Hacker News new | ask | show | jobs
by fhars 2391 days ago
No, it is not, it will just work most of the time in low level MCUs because compilers support this abuse for lack of clearly better options. C and C++ have no support whatsoever for dealing with interrupts: volatile does not introduce any memory fences, atomics are for sharing data between threads which you do not have in many embedded systems, and sig_atomic_t is only defined for situations where you have a posix-like runtime environment. So sharing data between an ISR and the main program is undefined in C, and the compilers are free to compile „volatile“ the way most people expect, but the language does not guarantee that it works.

It can be argued that the only kind of variable that can be shared safely between an ISR and the rest of the code is a volatile sig_atomic_t, but that is an argument from analogy and not from first principles, as the C abstract machine has no concept of ISR. The same goes for the argument that you should use atomic intrinsics, plausible, but still just an analogy.

(Just in case anyone was wondering if C as a language is close to the metal: no, it is not.)