C++ 中的比较
情况下比较两个 const char *
而言,这段 C++ 代码是否有效?
const char * t1="test1";
const char * t2="test2";
t2 = "test1";
if ( t1 == t2 ) {
cout << "t1=t2=" << t1 << endl;
}
就在不使用 strcmp
的
Is this valid code in C++ in terms of comparing two const char *
const char * t1="test1";
const char * t2="test2";
t2 = "test1";
if ( t1 == t2 ) {
cout << "t1=t2=" << t1 << endl;
}
without using strcmp
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,您正在比较指针值(即:地址),而不是它们的内容。该代码并不是无效的,它只是可能没有达到您的预期。
在 C++ 中,您应该避免
const char *
并使用std::string
:No, you are comparing the pointers values (ie: addresses), not their content. That code is not invalid, it just probably does not do what you expect.
In C++, you should avoid
const char *
and go forstd::string
:它是有效的,但它并不像你想象的那样。指针上的
==
检查它们是否指向相同的内存地址。如果在不同位置有两个相同的字符串,则它将不起作用。如果您熟悉 Python,这类似于该语言中
is
和==
之间的区别。It's valid, but it doesn't do what you think it does.
==
on pointers checks whether they point to the same memory address. If you have two identical strings at different locations, it won't work.If you're familiar with Python, this is similar to the distinction between
is
and==
in that language.