1

I'm starting to learn C++, and something useful from my main language Lua, is the ability to say:

print(true/false and 1 or 0)

1 or 0 being anything but it seems in c++ it doesnt work the same way?

What I tried for C++ was

cout << (score == 0) and "Valid";

But only a true if check seems to work

if (score == 0) {
    cout << "Valid";
} else {
    cout << "A";
}
Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
Albedo
  • 39
  • 1

2 Answers2

0
std::cout << ((score == 0) ? "Valid" : "A");
Jarod42
  • 203,559
  • 14
  • 181
  • 302
discape
  • 337
  • 1
  • 15
0

The << in your code isn't simply a syntax, it's an operator:

std::basic_ostream<CharT,Traits>::operator<<

Your attempt will not produce any compilation errors (assuming you have using namespace std;):

cout << (score == 0) and "Valid";
//        ^^ T/F ^^      ^^ T ^^

Apply some boolean algebra and that's equivalent to:

cout << true;  // if score is 0
cout << false; // if score is not 0

That's certainly not what you are trying to acheive.


Are there ways to do if statements inside a cout line?

if (score == 0)
    cout << "Valid";
else
    cout << "A";

You can do that using the conditional operator ?:

cout << (score == 0 ? "Valid" : "A");

But this approach is not guaranteed to work always. For example:

cout << (condition ? "String" : 1234);

Reason: Why in conditional operator (?:), second and third operands must have the same type?

Rearranging it like this will work:

condition ? cout << "String" : cout << 1234;

Now, talking about your Lua style:

print(true/false and 1 or 0)

I don't know Lua but that looks like a function. If you are looking for some template like that, try this:

template <typename T, typename U>
void conditionalPrint(const bool& condition, const T& arg1, const U& arg2)
{
    condition ? cout << arg1 : cout << arg2;    
}

You can use it like this:

conditionalPrint(score == 0, "Valid", "A");
conditionalPrint(someCondition, "String", 1234);

Of course, I'm not going to explain how that works because you're new to C++. I would still recommend the if-else way of doing it. Readability of your code is very important:

if (condition)
{
    cout << "true block";
}
else
{
    cout << "false block";
}

"Lot can be learned by comparing two lanugages and try to see if what can be done in one can also be done in the other, but usually what is idiomatic in one can be crap in the other. Anyhow, I had my fun with exploring the issue, but imho the conclusion is as important as the rest of the answer" - idclev

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53