问题描述
我昨天完成了C语言的编程考试。有一个我无法回答的问题,即使我今天学习了,也无法提出解决方案。
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.
所以我们有了这个:
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);
我知道如果 X = B!= C
为true,然后执行 A =(〜C)-A-
。如果为假,则执行 ++ C +(〜A)
。
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?
推荐答案
语句
X = B != C ? A=(~C) - A-- : ++C + (~A);
等于
if(B != C)
X = (A = (~C) - (A--));
else
X = ++C + (~A);
因此,表达式 A =(〜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.
这篇关于条件运算符? :"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!