+ 1

Explain please some C++ challenges.

1. Why the result is 3? int main() { int i = 0; cout << (i = 0 ? 1 : 2 ? 3 : 4); } 2. Why 2? int a; char c = 'a'; c += 3; c -= 'b'; a = c; cout << a;

16th Mar 2019, 6:17 PM
Kruzi 🇺🇦
Kruzi 🇺🇦 - avatar
4 Réponses
+ 5
Let's break down those ternary operators in the first question! i = 0 ? 1 : 2 ? 3 : 4 -> result is '3' First, we do: i = 0 ? 1 : 2 Maybe your confusion is that this means "does i equal 0? if so, i = 1; if not, i = 2". But for that, we'd have to use double equals signs: i == 0? 1 : 2 So what we have is actually this: "Assign to i the result of the expression: 0 ? 1 : 2" Since the conditional in this expression is simply "0", and 0 means FALSE, that translates to this: i = (False? 1 : 2) Therefore, i is now 2. Then we do 2? 3 : 4 or, to be more exact, i = 2 ? 3 : 4 And since in c++ any positive number other than zero gets interpreted as "true" if part of a conditional, this changes i = 2 to i = 3. Just to recap, "assign i to the value of this expression: (0 ? 1 : 2) (? 3 : 4)" yields 3. --- Second question! int a; // declares an int, currently with no value char c = 'a'; // declares a char with the value 'a' c += 3; // c was 'a', then we added 3 to its ASCII value; now it's 'd' c -= 'b'; // the difference between 'd' and 'b' is two, so now c == 2 a = c; // a is now 2 cout << a; // outputs 2 This code basically shows that you can operate on chars like you would with numbers. This is because all chars are basically arbitrary representations of a table of number, like ASCII or UNICODE. http://www.asciitable.com/
16th Mar 2019, 6:53 PM
Lucas Reis
Lucas Reis - avatar
+ 1
Thanks for answer, first one is correct, but how it works(
16th Mar 2019, 6:48 PM
Kruzi 🇺🇦
Kruzi 🇺🇦 - avatar
0
ye, i know maybe so it asks: if i = 0 true - 1 false - 2 and what next?)
16th Mar 2019, 6:53 PM
Kruzi 🇺🇦
Kruzi 🇺🇦 - avatar
0
great answer thanks)
16th Mar 2019, 7:06 PM
Kruzi 🇺🇦
Kruzi 🇺🇦 - avatar