Const 正确性 - Const 指针作为函数参数

发布于 2024-12-11 19:19:44 字数 303 浏览 0 评论 0原文

考虑像 The给定值 at (address) source is const 这样的函数

char* strcpy (char* destination, const char* source);

,因为该函数的作者想要表明 source 的值不会被 strcpy 更改。指针本身不会被 strcpy 改变。为什么不写

char* strcpy (char* destination, const char* const source);

提前非常感谢。

consider a function like

char* strcpy (char* destination, const char* source);

The given value at (address) source is const because the author of the function wants to show that the value of source will not be changed by strcpy. The pointer itself is not changed by strcpy to. Why not to write

char* strcpy (char* destination, const char* const source);

Many thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

℡寂寞咖啡 2024-12-18 19:19:44

指针本身是按值传递的,所以没有意义。

The pointer itself is passed by value, so there's no point.

尽揽少女心 2024-12-18 19:19:44

也可以这样写,但无论如何都不会影响调用者。

在第二种情况下,原型表明指针本身不应该被修改,但是调用者的指针无论如何都不能被修改,因为它在调用函数时被复制(按值传递)。

用 const 标记按值传递的变量仅对函数的实现者有用,作为明确其意图的一种方式。

It could as well be written like that, but it wouldn't affect the caller in any case.

In the second case the prototype says that the pointer itself should not be modified, but the caller's pointer cannot be modified anyway, because it is copied (passed by value) when calling the function.

Marking variables passed by value with const is useful only to the implementer of the function as a way to make his intents clear.

旧竹 2024-12-18 19:19:44

如果您尝试实现这两个功能,您会发现它们实际上是相同的。此时的 const 修饰符仅对函数体有意义,因为参数无论如何都是按值传递的。

error: function "strcpy" has already been defined
char* strcpy (char* destination, const char* const source)

You will see if you try to implement both functions, that they are actually the same. A const modifier at that point is only meaningful to the body of the function, since the argument is passed by value anyway.

error: function "strcpy" has already been defined
char* strcpy (char* destination, const char* const source)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文