✍️ Practice (Unary/Binary)
1. Dangers of Unary Operators
What is the output of the code below?
int a = 2;
int b = 3;
int c = 4;
a = ++b - c--; // this is the major line
Console.WriteLine (a+ " " + b + " " + c);
👀Hint
Try writing down the partial calculations step by step
int a = 2;
int b = 3;
int c = 4;
a = ++b - c--; // prefix rule: b=4 // postfix rule: c=4
// a=0 // c=3 now
Console.WriteLine (a+ " " + b + " " + c);
💡Solution
0 4 3
2. Dangers of Unary & Binary Operators
What is the output of the code below?
int a, b, c; // the variables are born
a = 5;
b=3;
c = ++ b - a;
a = a + c--;
c -=a;
a = ++b + ++c;
Console.WriteLine(a + " " + b + " " + c);
👀Hint
Try creating a table and filling in the values step by step
int a, b, c; // a=____ b=____ c=____
a = 5; // a=____ b=____ c=____
b=3; // a=____ b=____ c=____
c = ++ b - a; // a=____ b=____ c=____
a = a + c--; // a=____ b=____ c=____
c -=a; // a=____ b=____ c=____
a = ++b + ++c; // a=____ b=____ c=____
Console.WriteLine(a + " " + b + " " + c);
💡Solution
Full trace:
int a, b, c; // a=? b=? c=?
a = 5; // a=5 b=? c=?
b=3; // a=5 b=3 c=?
c = ++ b - a; // a=5 b=4 c=-1
a = a + c--; // a=4 b=4 c=-2
c -=a; // a=4 b=4 c=-6
a = ++b + ++c; // a=0 b=5 c=-5
Console.WriteLine(a + " " + b + " " + c);
Final Output:
0 5 -5