Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why GCC warns when casting an uninitialized volatile pointer to `void`?

Consider following:

int *volatile x;
(void)x;

GCC (from 5.x to 7.x) complains about it when -Wall is enabled:

warning: 'x' is used uninitialized in this function [-Wuninitialized]

The clang is silent about it.

For some reason, removing the volatile eliminates the warning.

Does the standard say that casting a volatile pointer even to void is undefined, while casting a normal pointer is fine? Or is that a GCC bug?


Disclaimer: The question is tagged as C/C++ on purpose. The GCC gives the same warning for both languages, and I'm interested of there is any difference.

like image 839
HolyBlackCat Avatar asked May 20 '26 16:05

HolyBlackCat


1 Answers

One of the behaviours of volatile for plain old data type like int * is to prevent the compiler from optimizing away the reading and writing to the variable. Please notice that int * here could be whatever like float or int.

So (void)x is meaning "read x and do nothing with the result" because x is volatile. If you read x and it's not pinned to a fixed position in memory (which the compiler might not know, only the linker does), then you're actually using it uninitialized.

If it's not volatile, although the compiler might read x anyway, it will likely avoid/optimize this (since it's a no-op), and silent the warning.

clang takes the safe road here, and since the linker directive could pin the variable x to some position (without clang knowing about it), consider that it's not worth triggering a warning without more evidence it's an issue.

like image 162
xryl669 Avatar answered May 22 '26 06:05

xryl669