[c] Why is volatile needed in C?

I'll mention another scenario where volatiles are important.

Suppose you memory-map a file for faster I/O and that file can change behind the scenes (e.g. the file is not on your local hard drive, but is instead served over the network by another computer).

If you access the memory-mapped file's data through pointers to non-volatile objects (at the source code level), then the code generated by the compiler can fetch the same data multiple times without you being aware of it.

If that data happens to change, your program may become using two or more different versions of the data and get into an inconsistent state. This can lead not only to logically incorrect behavior of the program but also to exploitable security holes in it if it processes untrusted files or files from untrusted locations.

If you care about security, and you should, this is an important scenario to consider.

Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to declaration

Component is part of the declaration of 2 modules What is the 'open' keyword in Swift? What’s the difference between “{}” and “[]” while declaring a JavaScript array? Getting error: ISO C++ forbids declaration of with no type What is an 'undeclared identifier' error and how do I fix it? Difference between int32, int, int32_t, int8 and int8_t forward declaration of a struct in C? How to initialize a vector in C++ Declare variable in SQLite and use it Initializing multiple variables to the same value in Java

Examples related to volatile

Volatile Vs Atomic What is the difference between atomic / volatile / synchronized? Why do we use volatile keyword? Volatile boolean vs AtomicBoolean Difference between volatile and synchronized in Java Volatile vs Static in Java Why is volatile needed in C? Volatile vs. Interlocked vs. lock What is the volatile keyword useful for?