If always returns true(如果总是返回真)
问题描述
我只是用 C++ 做一些实验,但我不明白为什么两个 if 语句都返回 true:
I'm just experimenting a bit with C++ but I can't figure out why both if-statements return true:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
cout << "Language?" << endl;
string lang;
cin >> lang;
if(lang == "Deutsch" || "deutsch")
{
cout << "Hallo Welt!";
}
else
{
return false;
}
if(lang == "English" || "english")
{
cout << "Hello World!";
}
else
{
return false;
}
return 0;
}
我对 C++ 和 stackoverflow 还是很陌生,所以如果这是一个愚蠢的或经常被问到的问题,我很抱歉,但我真的不知道更多.请帮忙!
I'm pretty new to C++ and stackoverflow so I'm sorry if that's an stupid or frequently asked question but I really don't know any further. Please help!
推荐答案
lang == "Deutsch" || "deutsch"
错了
lang == "Deutsch" || lang == "deutsch"
是对的
deutsch"单独返回内存中字符串的地址.这是永远不等于零.这意味着正确.
"deutsch" alone returns the address of the string in memory. which is always not equal to zero. which means true.
a == "hello" || "bob"
意思
(a == "hello") || "bob"
不管 a == "hello"
结果是什么(真或假),false ||"bob"
变成 false ||指向bob"的指针
.所有非空指针都是true
,所以这是false ||true
即 true
.
regardless of what a == "hello"
results in (true or false), false || "bob"
becomes false || pointer to "bob"
. All non-null pointers are true
, so this is false || true
which is true
.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
cout << "Language?" << endl;
string lang;
cin >> lang;
if(lang == "Deutsch" || lang == "deutsch")
{
cout << "Hallo Welt!";
}
else
{
return false;
}
if(lang == "English" || lang == "english")
{
cout << "Hello World!";
}
else
{
return false;
}
return 0;
}
这篇关于如果总是返回真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果总是返回真


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01