【问题标题】:Since arrays decay to pointers, why can't I apply const?既然数组衰减为指针,为什么我不能应用 const?
【发布时间】:2016-06-11 21:36:56
【问题描述】:

观察以下将const 应用于指针参数的方式:

void fn1(int * i){
  *i = 0; //accepted
   i = 0; //accepted
}
void fn2(int const* i){
  *i = 0; //compiler error
   i = 0; //accepted
}
void fn3(int *const i){
  *i = 0; //accepted
   i = 0; //compiler error
}
void fn4(int const*const i){
  *i = 0; //compiler error
   i = 0; //compiler error
}

我现在将尝试使用数组语法做同样的事情。
如您所知,数组在作为参数传递时会衰减为指针。
因此,行为应该是相同的。
但是,在使用数组语法时,我无法将 const 应用于衰减的指针。

void fn1(int i[]){
  *i = 0; //accepted
   i = 0; //accepted
}
void fn2(int const i[]){
  *i = 0; //compiler error
   i = 0; //accepted
}
void fn3_attempt1(int i[] const){ //<-- can't apply const this way
  *i = 0; //accepted
   i = 0; //compiler error
}
void fn3_attempt2(int i const[]){ //<-- can't apply const this way
  *i = 0; //accepted
   i = 0; //compiler error
}
...

有没有办法使用数组语法传递数组,但避免重新分配指针?

【问题讨论】:

  • 限定符必须在要限定的变量之前。 (感谢奥拉夫)
  • @DavidC.Rankin: const 准确地说是一个限定词。
  • int const 是不推荐使用的语法和过时的功能。限定符应该在类型之前。目前尚不清楚您的意思。 int i[]作为形参转换为int *
  • “如你所知,数组衰减为指针” - 我知道得更清楚。如前所述,这是错误的。
  • @Olaf 链接到限定符的折旧类型后?

标签: c arrays pointers parameter-passing constants


【解决方案1】:

无法使用数组语法指定指针的常量,因为它对实际数组没有意义。

无论如何,函数参数的数组语法有些混乱。如果您真的想要将函数参数设为const,请使用指针语法。

如果您使用 C99 引入的扩展数组语法之一来实现最小大小或多个动态维度,恐怕没有解决方案来指定指针的 constness。恕我直言,这不是一个真正的问题。

【讨论】:

  • 澄清一下:你可以很好地制作数组const。它只是转换后的指针本身,您不能用于语法。不确定现代编译器是否希望修改指针。
猜你喜欢
  • 2011-11-14
  • 2016-01-22
  • 2021-12-01
相关资源
最近更新 更多