问题描述
有关,我们需要使用一些 const volatile的TYPE *
指针一个嵌入式软件项目。现在,我们有期待像下面的一些计算功能:
For a embedded SW project we need to use some const volatile TYPE *
pointers. Now we have some calculation functions which are looking like following:
uint8 calc(const volatile uint8 *array, uint8 value) { ... }
两个变量的数据没有功能执行期间发生变化。
The data of both variables is not changing during the function execution.
调用code看起来像下面这样:
The calling code looks like following:
const volatile uint8 *array = (const volatile uint8 *)0x00010111;
uint8 value = 8;
uint8 result = calc(array, value);
现在的问题是,是有区别,如果我们设计的calucation功能,而不会挥发参数:
The question is now, would be there a difference, if we design the calucation functions without volatile arguments:
uint8 calc(const uint8 *array, uint8 value) { ... }
有关我们抛弃呼叫的挥发:
For the call we cast away the volatile:
uint8 result = calc((const uint8 *)array, value);
有第二溶液优点是更大的灵活性:我们可以使用功能也用于非挥发性的变量。但这是否有所作为,如果我们丢掉了动荡和我们的编译器做了一些优化强?
Pros for the second solution are more flexibility: We can use the function also for non volatile variables. But does it make a difference, if we cast away the volatile and our compiler does some strong optimizations?
推荐答案
您可以随时使用具有非易失性参数的函数。它只是在功能上code,如果他们挥发性(途中损失性能,最有可能的)处理给定的对象。它有点很难想象什么挥发性参数的函数(,因为他们可能会更改,恕不另行通知),可以理智地做到。当你写,你的情况的数据不反正改变,所以最灵活的解决方案是声明参数const和忘记挥发。
You can ALWAYS use the function with non-volatile arguments. Its just that the code in the function handles the given objects as if they were volatile (losing performance on the way, most likely). Its a bit hard to imagine what a function with volatile arguments ("because they might change without notice") could sensibly do. As you write, in your case the data doesn't change anyway, so the most flexible solution is to declare the parameters const and forget about volatile.
和pretty请使用uint8_t有,而不是一些自产自销的类型名称一样UINT8 - 它的标准自1996年
And pretty please, use "uint8_t" and not some homegrown type name like uint8 - its in the standard since 1996!
这篇关于const的挥发指针函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!