Section 2 Lecture 21

13_bc_urc
unreal-cpp

#1

Why doesn’t this line of code work.

return (Response[0] == 'y' || 'Y'); 

while this one works (the way you wrote it)

return (Response[0] == 'y') || (Response[0] == 'Y');

I know that we wrote this code a few lectures back but it worked until now that’s why i put it here. I could probably google this but i figured it was about time i checked out these forums and understood how they work. Thanks in advance.


#2

It may be an || but it still works very similar to an equation.
The first one will return the responce equal to y and Y.
The one that works returns responce y and responce Y


#3

The compiler reads this as:
evaluate if Response[0] == ‘y’ is true/false
OR
if ‘Y’

see the problem? The second evaluation after the OR has no real statement but just a letter.


#4

Ahhhhhh, stupid me. Thought i was being smart for making the code a bit more tidy. Thanks guys!!


#5

The way to look at if statements is like this (it might sound a bit convoluted now, but this will eventually become a natural way to think of it)

In simple terms, false is 0, true is NOT 0…

When you use AND, OR, or NOT operators (&&, || and ! respectively), you’re telling the computer to compare EACH side of that operator, and return based on the results

AND = return true if BOTH sides are true (non-zero)
OR = return true if EITHER side is true (non-zero)
! = return true if statement is false (zero)

So, using that logic with your statement
(Response[0] == ‘y’ || ‘Y’)

‘Y’ is a non-zero value (after all, it’s Y, not 0 :stuck_out_tongue: )

So, since the || operator tells the program to return true if EITHER side is true (non-zero), your statement would ALWAYS return true. Therefore, even if you typed in a chinese symbol, it would still return true.

That’s why you need to use the full statement
(Response[0] == ‘y’) || (Response[0] == ‘Y’);

Because you need both sides of the statement to do a comparison to your response.

Did that make enough sense?


#6

Yeah it did. Thanks for the help:D