1

I'm learning c++, and have had some moderate experience in other languages and I am transferring a lot of knowledge but not all knowledge is transferable.

My IDE has told me that this statement can be simplified but I don't see how?

if (answer[0] == 'y'||answer[0] == 'Y')
{
    return true;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Scott
  • 279
  • 3
  • 14

1 Answers1

3

You can use std::tolower:

if (std::tolower(answer[0]) == 'y')
    return true;

That's also how you should get input from the user when the case doesn't matter, instead of hardcoding cases.

Note: In theory, you need to make sure that answer[0] is in a valid range, or else you'll get undefined behavior (for non-ASCII characters and another std::locale for example). Your std::locale also matters in theory, but that's rarely the case if you are only dealing with ASCII characters.

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
  • so how will he check _if answer[0] is in a valid range_ **wouldn't it add another check to validate the range?** – Itban Saeed Jul 21 '17 at 06:22
  • @ItbanSaeed In theory yes, but not in practice. Characters *very* rarely exceed the range of an `unsigned char`. – Rakete1111 Jul 21 '17 at 06:23
  • Is there any performance improve with `std::tolower` or it just a choice of syntax? – Shiu Chun Ming Jul 21 '17 at 06:25
  • @ChunMingSHIU I very much doubt it. I would recommend my version because it's less duplication, but yeah, it's basically your choice. – Rakete1111 Jul 21 '17 at 06:27
  • 2
    Usual reminder: you cannot pass a `char` straight to `tolower`, you *have* to cast it to `unsigned char`, otherwise you risk undefined behavior. Your program *will* crash with at least one widely used C runtime library. That's a -1 until you fix this answer. – Matteo Italia Jul 21 '17 at 06:36
  • @MatteoItalia But if I pass for example a `1`, do I still have to cast? I thought that if you could guarantee that the value is within the range of an `unsigned char`, you're safe? – Rakete1111 Jul 21 '17 at 06:37
  • 1 is fine, the problem arises when you get negative `char`s. See here for a complete explanation https://stackoverflow.com/a/45007070/214671 – Matteo Italia Jul 21 '17 at 06:40
  • 1
    I very much doubt this is what OP's IDE had in mind. – Chris Drew Jul 21 '17 at 07:51
  • @Chris True, but it is still a valid answer to "How can this statement be simplified". With just the snippet the OP posted, it is impossible to know. – Rakete1111 Jul 21 '17 at 07:53