2016-02-28 23 views
3

观察到const可以应用于一个指针参数有以下几种:由于数组衰减为指针,为什么我不能应用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 
} 
... 

是否有任何的方式来传递使用数组语法的阵列,但要避免重新分配指针?

+0

限定符必须*先于*变量才能被限定。 (感谢Olaf) –

+0

@ DavidC.Rankin:'const'是一个精确的_qualifier_。 – Olaf

+1

'int const'是不建议使用的语法和过时的功能。限定符应该在类型前面。目前尚不清楚你的意思。 'int i []'作为形式参数转换为'int *' – Olaf

回答

6

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

无论如何,函数参数的数组语法都有些混乱。它你真的想要使函数参数const,使用指针语法。

如果您使用C99引入的扩展数组语法中的最小尺寸或多个动态尺寸,恐怕没有办法指定指针的常量。这不是一个真正的问题恕我直言。

+0

澄清:你可以使数组成为'const'。它只是转换的指针本身,你不能用于语法。不知道现代编译器是否想要修改指针。 – Olaf

相关问题