为什么 strcpy 将 const char* 用于 src 而不是 char *? [英] Why strcpy takes const char* for src instead of char *?

查看:49
本文介绍了为什么 strcpy 将 const char* 用于 src 而不是 char *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了自己的 strcpys 以查找 src as const char* & 之间是否有任何区别.char *,但没有发现以下 2 & 之间有任何区别两者的工作方式相同.

I implemented my own strcpys to find if there is any difference between src as const char* & char *, but don't find any difference between the following 2 & both worked the same.

char * my_strcpy(char*dest, char* src)
{
    while ('\0' != *src)
        *dest++ = *src++;
    *dest++ = '\0';
        return dest;
}

char * my_strcpy2(char*dest, const char* src)
{
    while ('\0' != *src)
        *dest++ = *src++;
    *dest++ = '\0';
    return dest;
}

strcpy 是否有任何理由将源指针作为 const char* 而不是 char* ?

Is there any reason that the strcpy takes the source pointer as const char* instead of char*?

推荐答案

strcpy 是否有任何理由将源指针作为 char* 而不是 const char* ?

Is there any reason that the strcpy takes the source pointer as char* instead of const char*?

源指针应该是const char *.原因对于所有不打算在函数内部意外更改源的函数(不仅仅是 strcpy)都很常见.

The source pointer should be const char *. The reason is common for all functions (not just strcpy) that do not intend to change the source accidentally inside the function.

该做法适用于 strcpy 等库函数或您自己的自定义函数.与像 strcpy 这样的库函数一样,源代码不可能意外改变.但是对于您自己(或其他所有人)的自定义函数,任何事情都可能发生.如果你确实意外地修改了它,那么你会得到一个编译错误告诉你.这就是 const 发挥作用的时候.

The practice applies to both library functions like strcpy or your own custom functions. As with library function like strcpy there is no chance that the source is accidentially changed. But for your own (or everyone else) custom function, anything can happen. And if you do modify it accidentially, then you would get a compile error telling you so. And that's when the const is making a difference.

这篇关于为什么 strcpy 将 const char* 用于 src 而不是 char *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆