交换两个值时,函数的输入必须是两个 const 指针并且 return 应该是 void

While swapping two values, the input of the function must be two const pointers and the return should be void

我已经编写了通常使用指针传递值的代码我的问题是如何传递这些值,即 a 和 b 作为常量指针,如果还没有的话。

void swap(int *x, int *y) 
    {
       int tmp;
       tmp = *x;
       *x = *y;
       *y = tmp;    
       return;
    } 
     
int main () {

   int a = 20;
   int b = 12345;
 
   printf("Before swap, value of a : %d\n", a );
   printf("Before swap, value of b : %d\n", b );
   swap(&a, &b);
   printf("After swap, value of a : %d\n", a );
   printf("After swap, value of b : %d\n", b );
 
   return 0;
}

参数按值传递,值不是const或非const;只有对象可以这样限定。您可以限定函数参数(它们是初始化为参数值的对象),这仅意味着该函数不会更改参数的值:

void swap(int * const x, int * const y)
{
    // x and y are not changed, although the objects they point to are changed.
    int temporary = *x;
    *x = *y;
    *y = temporary;
}

如果你想让参数类型指向const对象,那也是可以的。只要一个指针指向一个没有用const定义的对象,就定义了通过转换去掉const并用它来修饰对象的行为:

void swap(const int *x, const int *y)
{
    /* ncx and ncy are set to the original pointers to non-const
       that became the pointers to const that are x and y.
    */
    int *ncx = (int *) x, *ncy = (int *) y;
    int temporary = *ncx;
    *ncx = *ncy;
    *ncy = temporary;
}
C中的

const一般在类型之后,而*是类型的一部分,所以整型指针常量的类型声明是:

int * const

您可能已经尝试过 int const *,但发现它不起作用。那是因为,重复一下,通常 const 适用于它左边的东西。

观点:这就是为什么我讨厌先写const,比如const int。它之所以有效,是因为该语言有一个特例 - 如果 const 左边没有任何东西,它适用于它右边的东西 - 而且由于大多数人通过示例学习,所以 [=12= 的每次出现] 在类型声明的开头有助于 mis-teaching 试图学习该语言的人。

提示:我喜欢读和说 const 作为“which is constant”,因为这个短语明确指的是它前面的东西,所以它匹配 a 的部分的 left-to-right 顺序类型声明:int const 读作“一个常量整数”,int * const 读作“一个常量整数地址”。

将它与您的 swap 函数放在一起,我们得到

void swap(int * const x, int * const y)

观点:这也是我不喜欢 * 在声明中“触及”名字的原因。我做 int * foo 而不是 int *foo 因为它与其他类型声明如 int * const foo 更一致,我认为这比与 *foo 等取消引用中的一元运算符位置的一致性更重要.

但是您应该知道,在 C 中,或者至少在 C 的所有真实和最可想象的实现中,它实际上并没有改变代码行为来使函数参数 const 像那样 - 参数本身是对函数私有,因此函数无法更改它。它可以实际对实际代码产生影响的唯一方法是,如果你有一个 C 编译器,它可以更好地优化一个函数,如果你告诉它它不会修改它自己的参数,但大多数优化编译器只能注意到是否参数未在函数内修改。当然,它仍然可以作为一种方式告诉阅读您的代码的人您对参数的意图是什么,并且如果您习惯于在没有特定意图更改它们的任何时候声明事物为常量,那么您您更有可能让计算机捕捉到某些错误(例如,如果您的参数名称与函数中的变量相似,并且您打算修改一个但不小心输入了另一个 - 如果另一个是 const,简单的工具可以抓住错误)。