I've done my programming exam in C yesterday. There was a question I could not answer, and even though I've studied today I can't come up with a solution.
So we have this:
int A= -1 , B= -2, C= -3, X=1;
X = B != C ? A=(~C) - A-- : ++C + (~A);
printf("A= %d B= %d C =%d X=%d \n", A,B,C,X);
I know this operator functions if X = B != C
is true then A=(~C) - A--
is executed. If it's false, ++C + (~A)
is executed.
Can anyone tell me and explain what are the values of A, B, C and X in that printf
?
NEW
This was included in a question that asks to do a "trace" to the whole program:
#include <stdio.h>
void main(){
int A= -1 , B= -2, C= -3, X=1;
X = B != C ? A=(~C) - A-- : ++C + (~A);
printf("A= %d B= %d C =%d X=%d \n", A,B,C,X);
if(~A){
printf("\n out1\n");
C= A | B
printf("A= %d B= %d C =%d X=%d \n", A,B,C,X);
C= C <<1;}
if(A^B){
printf("\n out2\n");
C= B & A
B += 2
X= X>>1
printf("A= %d B= %d C =%d X=%d \n", A,B,C,X);
By the way can anyone tell me what does it mean those if
conditions?
The statement
X = B != C ? A=(~C) - A-- : ++C + (~A);
is equivalent to
if(B != C)
X = (A = (~C) - (A--));
else
X = ++C + (~A);
So, the expression A = (~C) - (A--)
invokes undefined behavior. In this case nothing good can be expected.
That said, this is a faulty question and shouldn't be asked in an examination. Or it could be asked with multiple choice answers as long as one option states that the code will invoke undefined behavior.
This question should never be on an exam, because it contains undefined behavior.
Specifically, this assignment A = (~C) - A--
modifies A
twice - in the --
compound assignment, and in the assignment itself. Since there is no sequence point in between the two, the behavior is undefined.
Note: This does not mean that the program is not going to print anything. It would most definitely produce some output on most platforms. However, none of that matters, because C the program is invalid in its entirety: it can produce any output it chooses to, produce no output, or even crash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With