If always returns true [duplicate]
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;
}
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!
Solution 1:
lang == "Deutsch" || "deutsch"
is wrong
lang == "Deutsch" || lang == "deutsch"
is right
"deutsch" alone returns the address of the string in memory. which is always not equal to zero. which means true.
a == "hello" || "bob"
means
(a == "hello") || "bob"
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;
}
Solution 2:
The expression lang == "Deutsch" || "deutsch"
is actually equivalent to (lang == "Deutsch") || ("deutsch")
. The second part of the expression is a const char*
with a non-zero value, which means it will evaluate to true
. The same applies to your second if
statement.
You meant to write lang == "Deutsch" || lang == "deutsch"
.
Solution 3:
The sentence:
if(lang == "Deutsch" || "deutsch")
is interpreted by the compiler as this:
"IF lang is equal to "Deutsch" OR the memory address of the string "deutsch" is not equal to 0 THEN...
Remember that in C/C++ any expression that is not zero, is considered to be TRUE. The expression "deutsch" is a string constant, which as an expression, returns its starting address, which is likely not 0.