-3

I'm having an issue with boolean and logical operators. I'm trying to get wantsToppings to evaluate to true if toppings equals 'T' or 't', but this code evaluates to true, regardless of user input. I'm not sure what I am missing, but I know I gotta be missing something.

Thanks for any help.

cout << "Toppings wanted (T for toppings/N for no toppings)? ";
cin >> toppings;

if (toppings == 't' || 'T'){
    wantsToppings = true;
} else {
    wantsToppings = false;
}
Radiodef
  • 37,180
  • 14
  • 90
  • 125
srallen87
  • 35
  • 1
  • 2

2 Answers2

3

You are missing how logical operators work. Here is what you do:

if (toppings =='t' || 'T')

and here is how it's done:

if (toppings =='t' || toppings == 'T')

You don't really need the complexity of the if either, it could just be:

wantsToppings = (toppings == 't' || toppings == 'T');
K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • Wow, I feel like an idiot. Thanks! – srallen87 Sep 14 '14 at 23:50
  • Not to poke the beesnest, but what's the logic behind the statement? I cannot seem to find a good explanation of why you have to reference the variable twice. – srallen87 Sep 14 '14 at 23:53
  • `expression || expression`, so `toppings == 't'` is *one* expression, and `toppings == 'T'` is another, to test one or the other, you OR the two expressions. – crashmstr Sep 14 '14 at 23:56
  • @srallen87, FWIW, C++ can be more versatile given a library for it. For example, you could make `if (toppings {'t', 'T'})` work. Of course you can also use `std::toupper` or `std::tolower` to halve the number of tests. – chris Sep 15 '14 at 00:03
  • Sorry, I lied. Initializer lists can't be used like that. You could get close, though. – chris Sep 15 '14 at 00:11
1

The expression

if (toppings == 't' || 'T')

does not mean to toppings is either of 't' or 'T', but rather essentially (it's in fact a little bit more complicated than this once you factor in lazy evaluation):

  • evaluates each sub-expression (the expression toppings == 't' and the expression 'T')
  • convert results of those expressions to boolean values if required
  • perform the logical or (||) of the above boolean values

Now 'T' is a char which gets promoted to the boolean value true, hence the result is always true.

As others have pointed out, the expression you are looking for is

if (toppings == 't' || toppings == 'T')
SleuthEye
  • 14,379
  • 2
  • 32
  • 61