I have a Visual C++ program that opens a file in one thread with FILE* fp = fopen(...). I want that thread to block on an event object while another thread reads the file, then signals the blocked thread when it is done, which will then close the file. Because fp is shared between threads, I have declared it as volatile FILE* fp. However, fread() won’t accept a volatile as its FILE* argument. I tried using a local pointer, with FILE* fpLocal = fp; in the thread that will call fread(), but that got me this:
Error: a value of type "volatile FILE*" cannot be assigned to an entity of type "FILE*"
Naturally, this has me worried that maybe I’m making a mistake by trying to open a file in one thread and read it in another to begin with, though I don’t see why (yet).
Can someone help me with this? Why can’t I assign a volatile FILE* to a FILE*?
Why can’t I assign a
volatile FILE*to aFILE*?Because C++ has strict type checking and you cannot assign types that do not match to each other.
One needs to use casting operators if that be the case, however it is important to note that using them incorrectly might lead to Undefined Behaviors as well.
This behavior is same as for the
constqualifier.As a side note as already mentioned in comments,
volatileis not the way to go here.