Reputation: 47
So I have a question about bool
variables.
This is a program which checks whether the due is payed on time and if it is not, it is multiplied by 1.10.
#include <iostream>
using namespace std;
int main()
{
float Dues;
cout<<"Enter ammount: \n";
cin>>Dues;
cout<<"On time? (y/n)";
char yn;
cin>>yn;
bool Overdue = yn !="y"; //TRUE (1) if it is late, FALSE (0) if it is on time
float AmountDue;
AmountDue = Overdue ? Dues*1.10 : Dues;
cout<<"Ammount due: ";
cout<<<<AmountDue;
return 0;
}
I don't undestand the logic of the bool
We have
bool Overdue = yn !="y";
Now this is my understaning of the logic of the bool and it is NOT right
If "n" is entered => N is NOT Y which is CORRECT therefore the bool is true => 1
If "y" is entered => Y is NOT Y which is WRONG, therefore fasle => 0
But it is actually the other way around and I can't explain it logically to myself.
On what logic is based bool Overdue = yn !="y";
?
Upvotes: 1
Views: 142
Reputation: 10613
In addition to jrok's answer the problem you are encountering is that you assume that lowercase and uppercase characters are the same thing. They are NOT. 'y' and 'Y' are two different characters. Same thing for 'n' and 'N'.
You write:
If "n" is entered => N is NOT Y which is CORRECT therefore the bool is true => 1
No. 'n' is not 'y'.
If "y" is entered => Y is NOT Y which is WRONG, therefore fasle => 0
It's CORRECT. 'y' is NOT 'Y'.
Try this instead:
bool Overdue = (yn != 'n') && (yn != 'N');
Upvotes: 2
Reputation: 55395
The reason for unexpected behaviour is that you're comparing a char
with a string literal "y"
. String literals are of type const char[n]
where n
is the length of the literal including the terminating NUL character.
Compare with a character literal instead:
yn != 'y'
When you say this: yn != "y"
, the char gets promoted to int
and the string literal decays to const char*
. How is this supposed to behave is unspecified by the standard.
The result of the expression gets stored in bool Overdue
. When yn
holds 'n'
, the expression is true
('n' is indeed different than 'y') so true
will be stored, and vice versa).
Upvotes: 2