Questions about char | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Questions about char

cout << (char('a'+1)=='b'); // outputs 1 Question 1: What does 'a'+1 mean? I'm guessing that it's the next letter of the alphabet? Question 2: Why do we need brackets around 'a'+1? I don't often see brackets after other data types... Question 3: Why do we need brackets around char('a'+1)=='b'? Is this analogous to " " for string? Question 4: Why isn't there a 'bool' in front of (char('a'+1)=='b'); ? After all, 1 is a boolean expression...

27th Jul 2020, 5:09 AM
Solus
Solus - avatar
1 Answer
0
1st Ans:the expression 'a'+1 is evaluated like this: 'a' is first promoted to int.it becomes 97 to which 1 is then added to give 98. 2nd Ans:the char() in char('a'+1) creates a temporary char variable.Please note that is not type casting.The expression is just meant to create a temporary char variable and then initializes it with the value 98 obtained above.To verify this,try running this code:cout<<('a'+1)<<char('a'+1); And note the difference. 3rd Ans:we need the brackets around the expression in the 2nd ans since the operator << has a higher precedence than ==.Without those brackets,the entire expression would have been evaluated like this (cout<<char('a'+1))=='b'; and this would be a terrible compiler error. 4th Ans:we don't need explicit casting to bool since equivalence operators (==,!=) when applied to built-in types,always return a bool
27th Jul 2020, 5:51 PM
Anthony Maina
Anthony Maina - avatar