C ++字符串字面量比较 [英] C++ Comparison of String Literals

查看:170
本文介绍了C ++字符串字面量比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个c ++新手(只是oldschool c)。我的儿子要求帮助这个,我无法解释。如果他问我如何比较字符串,我会告诉他使用strcmp(),但这不是让我困惑。这是他问的:

I'm a c++ newbie (just oldschool c). My son asked for help with this and I'm unable to explain it. If he had asked me "how do I compare strings" I would have told him to use strcmp(), but that isn't what is confusing me. Here is what he asked:

int main() 
{ 
  cout << ("A"< "Z");
}

将打印1

int main() 
{ 
  cout << ("Z"< "A");
}

也会打印1,但

int main() 
{ 
  cout << ("Z"< "A");
  cout << ("A"< "Z");
}

然后打印10.单独两个cout语句打印1,行我得到不同的答案?

will then print 10. Individually both cout statements print 1, but executed in a row I get a different answer?

推荐答案

您正在比较内存地址。显然,你的编译器将字符串字面量放在内存中的顺序遇到他们,所以第一个是较少比第二个。

You are comparing memory addresses. Apparently your compiler places the string literals in memory in the order it encounters them, so the first is "lesser" than the second.

因为在第一个片段它看到 A第一和Z秒,A较小。由于在第二个中看到Z,Z较小。在最后一个片段中,当第二个命令滚动时,它已经放置了字母A和Z。

Since in the first snippet it sees "A" first and "Z" second, "A" is lesser. Since it sees "Z" first in the second, "Z" is lesser. In the last snippet, it already has literals "A" and "Z" placed when the second command rolls around.

这篇关于C ++字符串字面量比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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