const int与int const作为C ++和C中的函数参数

时间:2008-10-02 14:11:02

标签: c++ c const

快速提问:

int testfunc1 (const int a)
{
  return a;
}

int testfunc2 (int const a)
{
  return a;
}

这两个功能在每个方面都相同还是有区别?我对C语言的答案感兴趣,但如果C ++语言中有一些有趣的东西,我也想知道。

9 个答案:

答案 0 :(得分:321)

诀窍是向后(从右到左)阅读声明:

const int a = 1; // read as "a is an integer which is constant"
int const a = 1; // read as "a is a constant integer"

两者都是一回事。因此:

a = 2; // Can't do because a is constant

当您处理更复杂的声明时,阅读倒退技巧特别有用,例如:

const char *s;      // read as "s is a pointer to a char that is constant"
char c;
char *const t = &c; // read as "t is a constant pointer to a char"

*s = 'A'; // Can't do because the char is constant
s++;      // Can do because the pointer isn't constant
*t = 'A'; // Can do because the char isn't constant
t++;      // Can't do because the pointer is constant

答案 1 :(得分:165)

const TT const完全相同。使用指针类型会变得更复杂:

  1. const char*是指向常量char
  2. 的指针
  3. char const*是指向常量char
  4. 的指针
  5. char* const是指向(可变)char
  6. 的常量指针

    换句话说,(1)和(2)是相同的。制作指针(而不是指针)const的唯一方法是使用后缀 - const

    这就是为什么许多人更喜欢总是将const放在类型的右侧(“东方const”风格):它使其位置相对于类型一致且易于记忆(它也似乎有趣)让初学者更容易教学。)

答案 2 :(得分:13)

没有区别。它们都声明“a”是一个无法更改的整数。

差异开始出现的地方是使用指针时。

这两个:

const int *a
int const *a

声明“a”是指向不变的整数的指针。 “a”可以分配给,但“* a”不能分配。

int * const a

声明“a”是一个指向整数的常量指针。 “* a”可以分配给,但“a”不能分配。

const int * const a

声明“a”是一个指向常量整数的常量指针。 “a”和“* a”都不能分配给。

static int one = 1;

int testfunc3 (const int *a)
{
  *a = 1; /* Error */
  a = &one;
  return *a;
}

int testfunc4 (int * const a)
{
  *a = 1;
  a = &one; /* Error */
  return *a;
}

int testfunc5 (const int * const a)
{
  *a = 1;   /* Error */
  a = &one; /* Error */
  return *a;
}

答案 3 :(得分:7)

Prakash是正确的,声明是相同的,虽然对指针的更多解释可能是有序的。

“const int * p”是指向int的指针,该int不允许通过该指针更改int。 “int * const p”是指向int的指针,无法将其更改为指向另一个int。

请参阅http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.5

答案 4 :(得分:5)

const intint const相同,C中的所有标量类型都是如此。通常,不需要将标量函数参数声明为const,因为C的调用-value语义意味着对变量的任何更改都是其封闭函数的局部变量。

答案 5 :(得分:4)

这不是一个直接的答案,而是一个相关的提示。为了保持正确,我总是使用对流“把const放在外面”,其中“外面”是指最左边或最右边。这样就没有混淆 - const适用于最接近的东西(类型或*)。如,



int * const foo = ...; // Pointer cannot change, pointed to value can change
const int * bar = ...; // Pointer can change, pointed to value cannot change
int * baz = ...; // Pointer can change, pointed to value can change
const int * const qux = ...; // Pointer cannot change, pointed to value cannot change

答案 6 :(得分:3)

是的,它们仅适用于int

int*

不同

答案 7 :(得分:3)

我认为在这种情况下它们是相同的,但这是一个有关顺序的例子:

const int* cantChangeTheData;
int* const cantChangeTheAddress;

答案 8 :(得分:3)

它们是相同的,但在C ++中,有一个很好的理由始终在右边使用const。你会在任何地方保持一致,因为const成员函数必须以这种方式声明:

int getInt() const;

它将函数中的this指针从Foo * const更改为Foo const * constSee here.

相关问题