避免在函数调用中从 volatile static uint8_t 转换为 uint8_t?
我目前有这段代码:
static void func( uint8_t var );
static volatile uint8_t foo;
int main() {
/* Here we have to cast to uint8_t */
func( (uint8_t) foo );
/* This will not compile */
func( foo );
}
有没有办法避免函数调用中的强制转换?
I currently have this code:
static void func( uint8_t var );
static volatile uint8_t foo;
int main() {
/* Here we have to cast to uint8_t */
func( (uint8_t) foo );
/* This will not compile */
func( foo );
}
Is there a way to avoid the cast in the function call?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不必显式强制转换。第二种形式对于任何符合标准的 C 编译器都完全有效。
您只需要像这样进行转换:
You don't have to explicitly cast. The second form is completely valid for any standards compliant C compiler.
It is only something like this where you would need to cast:
这是使用 gcc 为我编译的。 (我必须实际定义该函数,并包含头文件。)
This compiles for me using gcc. (i had to actually define the function, and include the header file.)
我猜您正在尝试将指针传递给变量,并且在编辑您的问题时,您删除了指针声明以简化,但这也改变了您的问题。如果您将值传递给函数,则没有任何问题。
现在,如果您传递指针,则 volatile 修饰符告诉编译器应该期望变量的值通过编译代码以外的方式更改。您确实不应该将易失性变量作为非易失性参数传递给函数。函数本身必须更改为具有易失性参数,并重新编译。然后准备函数(带有易失性参数)来处理易失性变量。
I guess you are trying to pass a pointer to the variable and, while editing your question, you removed the pointer declaration in order to simplify, but that also changed your question. If you are passing a value to the function, there isn't any problem.
Now, if you are passing a pointer, the volatile modifier tells that the compiler should expect the value of the variable to change by means other than the compiled code. You really shouldn't pass a volatile variable as a non-volatile parameter to a function. The function itself must be changed to have the volatile parameter, and recompiled. Then function (with volatile parameter) is prepared to deal with a volatile variable.