tags:

views:

67

answers:

3

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

+4  A: 

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.

wilx
+4  A: 

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);
caf
+1  A: 

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.)

Jens Gustedt