C# Programming - Control Instructions - Discussion

Discussion Forum : Control Instructions - General Questions (Q.No. 7)
7.
What will be the output of the C#.NET code snippet given below?
char ch = Convert.ToChar ('a' | 'b' | 'c'); 
switch (ch)
{
    case 'A': 
    case 'a':
    Console.WriteLine ("case A | case a");
    break;
    
    case 'B': 
    case 'b':
    Console.WriteLine ("case B | case b");
    break;
    
    case 'C':
    case 'c':
    case 'D':
    case 'd':
    Console.WriteLine ("case D | case d");
    break;
}
case A | case a
case B | case b
case D | case d
Compile Error
No output
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
13 comments Page 1 of 2.

Shankar Jat said:   1 decade ago
0 and 1 return in case of ||(OR) , not in case of |....
'a' --> 0110 0001
'b' --> 0110 0010
'c' --> 0110 0011
'a'|'b' ---> 01100011
('a'|'b')|'c' --> 01100011('c')
-----------------
So,

'a'|'b'|'c' --> 0110 0011
Thats why it return 'c'.

And match with 'c' after that there is break statement till got break....so o/p is case D | case d.
(2)

Ashwini Shelke said:   1 decade ago
The trick behind this question is it first will convert a character to its bit value and performs or operation and final result of or operation will be returned as a char.

Ex. convert.ToChar('0'|'1')

Here 0 will get its bit value as 000 and 1 as 001 and or result of these two ll be 1 so it will return 1. If it is & operation then it will return 0.
(2)

Rathi said:   1 decade ago
ASCII value of each char are,

'a' --> 0110 0001
'b' --> 0110 0010 (| - Bit wise OR)
'c' --> 0110 0011
-----------------
'a'|'b'|'c' --> 0110 0011 (it nothing but 'c')

In case c is true, then there is no Break after c, So it execute continuously

Therefore output is : [c]. case D | case d
(2)

Venkat said:   1 decade ago
I Can't able to understand it. Then why compiler not assign a / b to character 'ch' variable. I think left to right precedence base last 'c' is assign to 'ch' variable. Please clear my doubt's.

Rajveer singh said:   1 decade ago
First ch is assigned value 'a' then 'b' and at last 'c' because of the 'or', '|' operator, so what ever be the last value, will be assigned to c.

Mayank Kumar said:   8 years ago
Pleas e solve this Query .
What will be output. I can not understand logic.

char ch = Convert.ToChar('a' | 'B' | 'C'|'D' );

Karthickkumar A said:   2 years ago
I do not understand how the variable ch takes the value 'c'. Can somebody explain this, please?

Thanks.

Yelani said:   1 decade ago
I do not understand how the variable ch takes the value 'c'. Can somebody explain this please?
Thanks

Sushant said:   10 years ago
Can you tell me properly how it is working? Because how you decided to convert to ASCII value?

Shylender said:   1 decade ago
Can anyone explain it. I didn't understand.


Post your comments here:

Your comments will be displayed after verification.