为什么strrchr()返回`char *`而不是`const char *`?
函数 char* strrchr(const char *str, int ch)
返回一个指针(ch
所在的str
(const char *
)中.
因此我们可以编写以下代码而无需任何强制转换:
So we can write the following code without any cast:
#include <string.h>
int main()
{
const char CONSTSTR[] = "foo/bar/foobar.txt";
char *ptr = strrchr (CONSTSTR, '/');
*ptr++ = 'B';
*ptr++ = 'A';
*ptr++ = 'D';
}
返回char*
而不是const char*
有什么好处?
What is the advantage to return char*
instead of const char*
?
编辑:
正如 Shafik Yaghmour 指出的那样, strchr实现如何工作?
As a Shafik Yaghmour pointed out, there are very good answers to How does strchr implementation work?
因为我的代码是C ++,所以我将使用<cstring>
而不是<string.h>
.谢谢您的回答;-)
As my code is in C++, I will use <cstring>
instead of <string.h>
. Thanks for your answers ;-)
但是,迈克·西摩的答案最适合这个问题.我什至添加了下面的更详细的答案,以明确地说strrchr()
是C函数(不允许重载),该声明同时适合 const 和 non-const 字符串.因为strrchr()
可以用 non-const 字符串调用,所以返回的字符串也应该是 non-const .
However, the Mike Seymour's answer fits best the question. I have even added a more detailed answer below to clearly say as strrchr()
is a C function (overload not permitted), the declaration fits both const and non-const strings. Because strrchr()
can be called with a non-const string, the returned string should also be non-const.
在C语言中,函数必须像这样,或者在许多情况下强制用户使用躲猫猫强制转换:
In C, the function must either be like this, or force the user to use dodgy casts in many situations:
- 如果使用非
const
指针,则无法搜索const
字符串; - 如果它返回了
const
指针,则无法使用它来修改非const
字符串.
- If it took a non-
const
pointer, you couldn't search aconst
string; - If it returned a
const
pointer, you couldn't use it to modify a non-const
string.
在C ++中,应包括<cstring>
而不是已弃用的仅C标头.这将为您提供两个const正确的重载,这在C语言中是无法完成的:
In C++, you should include <cstring>
rather than the deprecated C-only header. That will give you two const-correct overloads, which couldn't be done in C:
const char* strchr(const char* s, int c);
char* strchr( char* s, int c);