Argument of type “volatile char *” is incompatible with parameter of type “const char *”

偶尔善良 提交于 2019-12-07 05:53:52

问题


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


回答1:


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



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/3457677/argument-of-type-volatile-char-is-incompatible-with-parameter-of-type-const

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!