I think I have a tricky question, but I'm sure you will be able to help me. Let's say I have a function like this:
char my_function (int example);
I use this function in multiple cases, sometimes the argument it receives is a volatile variable and sometimes a non-volatile variable. That cause some warnings when I compile my code that can be easily removed by using casts, but I want to understand which is the safer scenario and why.
Scenario 1:
Prototype: char my_function (int example);
int a;
volatile int b;
my_function (a); // Everything is fine.
my_function ((int)b); // Avoided the warning, by casting the variable and saying it's no longer volatile.
Scenario 2:
Prototype: char my_function (volatile int example);
int a;
volatile int b;
my_function(b); // Everything is fine.
my_function((volatile int)a); // Avoided the warning, by casting 'a' saying that now it's volatile.
I understand how volatile modifier works, I mostly use it because I program micro-controllers and I need to ensure that some of my variables are never optimized out when they are hardware modified. I am a bit confused about casting the volatile modifier and that is why I want to understand which is the safer scenario apart from just removing the warning.
volatile
is not a modifier, but a qualifier. There are no modifiers in C. And your question is not clear. Although you state different, your text lets suspect you do not know howvolatile
works. Revisit your C book or get a better one. And never cast an expression until you are aware of all implications. I have strong doubts.volatile
in conjunction with pointer parameters can make sense; if the data the pointer points at can change behind the scenes, that's crucial for the compiler to know. But simple value parameters marked volatile; that's tantamount to an abuse ofvolatile
.volatile
qualifier on the function argument/return type, not the variable being passed to the function.