-5

如何将 int 传递给期望const int的函数。

或者有没有办法修改 cont int 值?

编辑:我应该在前面提到这一点,我正在使用用于编程 pic 微控制器的 ccs c 编译器。fprintf 函数将常量流作为其第一个参数。它只会接受一个常量 int 并抛出编译错误,否则“Stream must be a constant in the valid range.”。

编辑 2: Stream 是一个常量字节。

4

2 回答 2

9

函数参数列表中的顶层const被完全忽略,所以

void foo(const int n);

完全一样

void foo(int n);

所以,你只需传递一个int.

唯一的区别在于函数定义,在第一个例子中,而在第二个例子中是可变的nconst所以这个细节const可以看作是一个实现细节,应该在函数声明中避免。例如,这里我们不想修改n函数内部:

void foo(int n); // function declaration. No const, it wouldn't matter and might give the wrong impression

void foo(const int n) 
{
  // implementation chooses not to modify n, the caller shouldn't care.
}
于 2013-08-18T09:44:36.610 回答
4

这不需要愚弄。期望类型参数的函数const int将愉快地接受类型参数int

以下代码可以正常工作:

void MyFunction(const int value);

int foo = 5;
MyFunction(foo);

因为参数是按值传递的,所以const实际上是没有意义的。唯一的作用是确保函数的变量的本地副本不被修改。您传递给函数的变量永远不会被修改,无论参数是否被视为const

于 2013-08-18T09:44:45.473 回答