Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
253 views
Welcome To Ask or Share your Answers For Others

1 Answer

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...