避免在函数调用中从 volatile static uint8_t 转换为 uint8_t?

发布于 2024-08-06 13:59:50 字数 263 浏览 3 评论 0原文

我目前有这段代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

厌倦 2024-08-13 13:59:51

您不必显式强制转换。第二种形式对于任何符合标准的 C 编译器都完全有效。

您只需要像这样进行转换:

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

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:

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 );  
}
噩梦成真你也成魔 2024-08-13 13:59:51
#include <stdint.h>

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

这是使用 gcc 为我编译的。 (我必须实际定义该函数,并包含头文件。)

#include <stdint.h>

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

This compiles for me using gcc. (i had to actually define the function, and include the header file.)

你好,陌生人 2024-08-13 13:59:50

我猜您正在尝试将指针传递给变量,并且在编辑您的问题时,您删除了指针声明以简化,但这也改变了您的问题。如果您将值传递给函数,则没有任何问题。

现在,如果您传递指针,则 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文