I need some help understanding why the following code compiles the way it does.
ID: 3841191 • Letter: I
Question
I need some help understanding why the following code compiles the way it does. These were questions that I recently had on test. The point of this test was to see our knowledge of "braces" locations within the code. So this code is missing braces.
1. What is the value after the following code executes?
int (donuts = 10;
if (donuts!= 10)
donuts = 0;
else
donuts += 2;
Answers:
A. 12
B. 10
C. 0
D. 2
I know the answer is 'A', but I am not clear on why. A similar question is posted below.
2. What is the value of donuts after the following code executes?
int donuts = 10;
if (donuts = 1)
donuts = 0;
else
donuts +=2;
Answers:
A. 12
B. 10
C. 0
D. 1
This answer is 'C', but again I am not clear on why.
Explanation / Answer
1.
int (donuts = 10;
if (donuts!= 10)
donuts = 0;
else
donuts += 2;
This code should not even compile since you have a variable name starting with '('. That's not allowed in C, C++ or in most of the languages (all the languages that I ever know), for that matter. Maybe it's a typo or copy-paste mistake.
Aside from that, by taking into account that it runs, here's how you get A as the answer:
'donuts' variable gets declared and initialized with 10 on the first line of the code.
On the second, donuts get checked for inequality with 10, donuts holds 10. So donuts != 10 is false, so it goes to the else part and it gets incremented by 2. It's very important to notice that you don't have braces for that if-else statement,
if(test)
do this
else
do this
It's okay to have it like that since you don't have more than on statement on each of the block. if you had like donuts+=2 and something like int a = 10;, then you'd get a syntax error.
2.
int donuts = 10;
if (donuts = 1)
donuts = 0;
else
donuts +=2;
This is a common mistake that most people would make, I'd done multiple times.
In the if statement, if you really look into it, you have an assignment operator '=' instead of an equality operator '=='.
So what that statement means is that, you're actually assigning 1 to donuts variable. And in C, C++, etc any integer other than 0 means True (0 is False), so the test passes and donut variable gets assigned the value 0.