Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument of type "volatile char *" is incompatible with parameter of type "const char *"

I have a function whose prototype is as follows:

void foo(const char * data);

Elsewhere in my code, I have a global variable declared as follows

volatile char var[100];

Whenever I try to do this:

foo(var);

The compiler throws up the following error message:

Argument of type "volatile char *" is incompatible with parameter of type "const char *"

Why is that the case? As I understand it, the variable in my function is not allowed to change the pointer or its contents. I understand that because my global variable is volatile, it could potentially change at any time, but seeing as it is perfectly legal to have a volatile const variable, I don't see why I am getting this compiler error.

Thanks

--Amr

like image 627
Amr Bekhit Avatar asked Aug 11 '10 11:08

Amr Bekhit


3 Answers

It's because implicit conversions can add qualifiers to the target of pointer types, but not remove them. So if you want your function to be able to accept volatile and/or const qualified pointers, you must declare it with both:

void foo(const volatile char * data);
like image 66
caf Avatar answered Oct 03 '22 06:10

caf


Because accessing a volatile variable using pointer to non-volatile is wrong. Either the object is volatile and then it should be accessed as such everywhere or you can access it as non-volatile and then it should not be marked as such. Make up your mind.

like image 27
wilx Avatar answered Oct 03 '22 06:10

wilx


If you want to handle a volatile argument in your function you must declare it as such:

void foo(const volatile char * data);

This would do the trick. But be aware that this also brings you all the overhead of volatile to the implementation of foo, i.e data[something] will be reloaded from memory at any point that you access it.

(Generally volatile is not so much of a good idea, unless you are doing device drivers or so. Even for parallel processing with threads it usually doesn't guarantee what you expect at a first site.)

like image 38
Jens Gustedt Avatar answered Oct 03 '22 06:10

Jens Gustedt