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

有没有办法避免函数调用中的强制转换?

4

3 回答 3

4

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

现在,如果你传递一个指针, volatile 修饰符告诉编译器应该期望变量的值通过编译代码以外的方式改变。您真的不应该将 volatile 变量作为非易失性参数传递给函数。必须将函数本身更改为具有 volatile 参数,然后重新编译。然后函数(带有 volatile 参数)准备处理一个 volatile 变量。

于 2009-09-24T18:55:37.357 回答
0

您不必显式转换。第二种形式对于任何符合标准的 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 );  
}
于 2009-09-24T18:52:18.563 回答
0
#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 为我编译。(我必须实际定义函数,并包含头文件。)

于 2009-09-24T18:57:02.657 回答