Ioakim Helen
Ioakim Helen

Reputation: 73

Use bool array in if statement c++

I'm a beginner to programming and Stackoverflow. I'm sorry for my bad formatting and my English. My question is if I can do the thing in the if brackets. Thank you :)

for(int i=0;i<A.size();++i)
{
     if(Alphabet[i]==false)
            cout<<A[i];
     else if(Alphabet[i]==true)
     {
         cout<<endl<<A[i];
     }
  }

Upvotes: 2

Views: 1755

Answers (3)

phantom
phantom

Reputation: 3342

Yes. You can compare boolean value to a boolean literal. It is, however, easier to simply use the bool value for the if statement. Doing that would look like this

if(!Alphabet[i]) // Originally if(Alphabet[i]==false)

and like this

else if(Alphabet[i]) // Originally else if(Alphabet[i]==true)

You don't even have to test for the second condition. Since it will always execute if the first statement doesn't you can replace it with an else statement. This would change your else if statement to just an else. Like this

else
{
    cout<<endl;
    cout<<A[i];
}

Upvotes: 2

Keith Thompson
Keith Thompson

Reputation: 263267

Assuming Alphabet is an array of bool, you're just testing the value of an element of that array. It's perfectly safe -- and it can be done much more simply than what you've written:

if (Alphabet[i]) {
    std::cout << A[i] << std::endl;
}
else {
    std::cout << A[i];
}

The only values a bool can have are true and false. Explicitly comparing a bool value for equality to true or false is needlessly redundant (and such comparisons can be dangerous in some contexts); just test the value of the value itself. Once you've tested whether it's true, there's no need to test again whether it's false; just use an else clause. If you need to test whether it's false, use the ! (logical "not") operator: if (! Alphabet[i]).

Finally, you're printing the value of A[i] unconditionally, so that part doesn't need to be inside either the if or the else:

std::cout << A[i];
if (Alphabet[i]) {
    std::cout << std::endl;
}

Upvotes: 1

CocoCrisp
CocoCrisp

Reputation: 815

Try to optimize the code as

If(Alphabet[I])

Or

If(!Alphabet[I])

Yes you can compare it the way you did,nothing wrong.

Thanks

Upvotes: 0

Related Questions