-1

I am trying to create a simple c++ program which prints out if char is Y or y, N or n or neither.

After debugging I have found out that the if(chr == 'Y' || 'y') statement is true even though char variable is 'N'. Can anybody tell me why this if statement is true and not false?

#include "pch.h"
#include <iostream>
using namespace std;

void main()
{
char chr = 'N';

if (chr == 'Y' || 'y')
{
    cout << "chr is y" << endl;

}
else if (chr == 'N' || 'n')
{
    cout << "chr is n" << endl;
}
else
{
    cout << "chr is something else" << endl;
}
}
Craig P H
  • 121
  • 2
  • 16
  • 3
    That doesn't do what you think it does. Use `chr == 'Y' || chr == 'y'` instead (and similar for `'n'` and `'N'`). – Qubit Oct 29 '18 at 15:27
  • 1
    The condition `chr == 'Y' || 'y'` means "chr is equal to 'Y'; Or 'y'." Note the lack of comparison in the second part of the sentence. Your sentence should be like "chr is equal to 'Y'; Or chr is equal to 'y'." – Some programmer dude Oct 29 '18 at 15:30
  • See also `std::toupper` and `std::tolower` so you only have to make one comparison. – Thomas Matthews Oct 29 '18 at 16:52

2 Answers2

3

This is not doing what you thing:

if (chr == 'Y' || 'y')

This is basically:

if (chr == 'Y' || true)

So in the end:

if (true)

You have to say what you compare:

if (chr == 'Y' || chr == 'y')

The operator == only takes one character, not a set of possible characters.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
1

Instead of this

if (chr == 'Y' || 'y')

You need

if ((chr == 'Y') || (chr == 'Y'))

Likewise for the 'N' and 'n'.

It is also possible do it with one comparison:

if (toupper((unsigned char)chr) == 'Y')

This way, maintainability is slighly improved as only one value has to be changed should the letter change (for a different localization, per example).

Blaze
  • 16,736
  • 2
  • 25
  • 44